当前位置: 首页>>代码示例>>C#>>正文


C# XmlSchemaCollection.Add方法代码示例

本文整理汇总了C#中System.Xml.Schema.XmlSchemaCollection.Add方法的典型用法代码示例。如果您正苦于以下问题:C# XmlSchemaCollection.Add方法的具体用法?C# XmlSchemaCollection.Add怎么用?C# XmlSchemaCollection.Add使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Xml.Schema.XmlSchemaCollection的用法示例。


在下文中一共展示了XmlSchemaCollection.Add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: TestAdd

		public void TestAdd ()
		{
			XmlSchemaCollection col = new XmlSchemaCollection ();
			XmlSchema schema = new XmlSchema ();
			XmlSchemaElement elem = new XmlSchemaElement ();
			elem.Name = "foo";
			schema.Items.Add (elem);
			schema.TargetNamespace = "urn:foo";
			col.Add (schema);
			col.Add (schema);	// No problem !?

			XmlSchema schema2 = new XmlSchema ();
			schema2.Items.Add (elem);
			schema2.TargetNamespace = "urn:foo";
			col.Add (schema2);	// No problem !!

			schema.Compile (null);
			col.Add (schema);
			col.Add (schema);	// Still no problem !!!

			schema2.Compile (null);
			col.Add (schema2);

			schema = GetSchema ("Test/XmlFiles/xsd/3.xsd");
			schema.Compile (null);
			col.Add (schema);

			schema2 = GetSchema ("Test/XmlFiles/xsd/3.xsd");
			schema2.Compile (null);
			col.Add (schema2);
		}
开发者ID:calumjiao,项目名称:Mono-Class-Libraries,代码行数:31,代码来源:XmlSchemaCollectionTests.cs

示例2: ValidaSchema

        /// <summary>
        ///     Valida se um Xml está seguindo de acordo um Schema
        /// </summary>
        /// <param name="arquivoXml">Arquivo Xml</param>
        /// <param name="arquivoSchema">Arquivo de Schema</param>
        /// <returns>True se estiver certo, Erro se estiver errado</returns>
        public void ValidaSchema(String arquivoXml, String arquivoSchema)
        {
            //Seleciona o arquivo de schema de acordo com o schema informado
            //arquivoSchema = Bll.Util.ContentFolderSchemaValidacao + "\\" + arquivoSchema;

            //Verifica se o arquivo de XML foi encontrado.
            if (!File.Exists(arquivoXml))
                throw new Exception("Arquivo de XML informado: \"" + arquivoXml + "\" não encontrado.");

            //Verifica se o arquivo de schema foi encontrado.
            if (!File.Exists(arquivoSchema))
                throw new Exception("Arquivo de schema: \"" + arquivoSchema + "\" não encontrado.");

            // Cria um novo XMLValidatingReader
            var reader = new XmlValidatingReader(new XmlTextReader(new StreamReader(arquivoXml)));
            // Cria um schemacollection
            var schemaCollection = new XmlSchemaCollection();
            //Adiciona o XSD e o namespace
            schemaCollection.Add("http://www.portalfiscal.inf.br/nfe", arquivoSchema);
            // Adiciona o schema ao ValidatingReader
            reader.Schemas.Add(schemaCollection);
            //Evento que retorna a mensagem de validacao
            reader.ValidationEventHandler += Reader_ValidationEventHandler;
            //Percorre o XML
            while (reader.Read())
            {
            }
            reader.Close(); //Fecha o arquivo.
            //O Resultado é preenchido no reader_ValidationEventHandler

            if (validarResultado != "")
            {
                throw new Exception(validarResultado);
            }
        }
开发者ID:njmube,项目名称:NFeEletronica.NET,代码行数:41,代码来源:Xml.cs

示例3: TestAddDoesCompilation

		public void TestAddDoesCompilation ()
		{
			XmlSchema schema = new XmlSchema ();
			Assert (!schema.IsCompiled);
			XmlSchemaCollection col = new XmlSchemaCollection ();
			col.Add (schema);
			Assert (schema.IsCompiled);
		}
开发者ID:calumjiao,项目名称:Mono-Class-Libraries,代码行数:8,代码来源:XmlSchemaCollectionTests.cs

示例4: clsSValidator

 public clsSValidator(string sXMLFileName, string sSchemaFileName)
 {
     m_sXMLFileName = sXMLFileName;
     m_sSchemaFileName = sSchemaFileName;
     m_objXmlSchemaCollection = new XmlSchemaCollection ();
     //adding the schema file to the newly created schema collection
     m_objXmlSchemaCollection.Add (null, m_sSchemaFileName);
 }
开发者ID:jeremyhallpdx,项目名称:pdxwrex,代码行数:8,代码来源:clsSValidator.cs

示例5: ParseString

        public NSTScorePartwise ParseString(string dataString)
        {
            //todo: parse string
            IList<NSTPart> partList = new List<NSTPart>();
            XmlTextReader textReader = new XmlTextReader(new FileStream("C:\\NM\\ScoreTranscription\\NETScoreTranscription\\NETScoreTranscriptionLibrary\\OtherDocs\\musicXML.xsd", System.IO.FileMode.Open)); //todo: pass stream in instead of absolute location for unit testing
            XmlSchemaCollection schemaCollection = new XmlSchemaCollection();
            schemaCollection.Add(null, textReader);

            NSTScorePartwise score;

            using (XmlValidatingReader reader = new XmlValidatingReader(XmlReader.Create(new StringReader(dataString), new XmlReaderSettings() { DtdProcessing = DtdProcessing.Parse }))) //todo: make unobsolete
            {
                reader.Schemas.Add(schemaCollection);
                reader.ValidationType = ValidationType.Schema;
                reader.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(ValidationEventHandler);

                XmlSerializer serializer = new XmlSerializer(typeof(NSTScorePartwise), new XmlRootAttribute("score-partwise"));
                score = (NSTScorePartwise)serializer.Deserialize(reader);

                /*
                while (reader.Read())
                {
                    if (reader.IsEmptyElement)
                        throw new Exception(reader.Value); //todo: test

                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            switch (reader.Name.ToLower())
                            {
                                case "part-list":
                                    break;
                                case "score-partwise":
                                    break;
                                case "part-name":
                                    throw new Exception("pn");
                                    break;
                            }
                            break;
                        case XmlNodeType.Text:

                            break;
                        case XmlNodeType.XmlDeclaration:
                        case XmlNodeType.ProcessingInstruction:

                            break;
                        case XmlNodeType.Comment:

                            break;
                        case XmlNodeType.EndElement:

                            break;
                    }
                }*/
            }

            return score;
        }
开发者ID:NathanMagnus,项目名称:NETScoreTranscription,代码行数:58,代码来源:XMLParser.cs

示例6: Main

        static void Main(string[] args)
        {
            if (args.Length != 4)
            {
                Console.WriteLine("Invalid parameter count. Exiting...");
                return;
            }

            string xmlFile = args[0];
            string xdsFile = args[1];
            string xdsNamespace = args[2];
            string outputFile = args[3];

            try
            {
                XmlSchemaCollection cache = new XmlSchemaCollection();
                cache.Add(xdsNamespace, xdsFile);

                XmlTextReader r = new XmlTextReader(xmlFile);
                XmlValidatingReader v = new XmlValidatingReader(r);
                v.Schemas.Add(cache);

                v.ValidationType = ValidationType.Schema;

                v.ValidationEventHandler +=
                    new ValidationEventHandler(MyValidationEventHandler);

                while (v.Read()) { } // look for validation errors
                v.Close();
            }
            catch (Exception e)
            {
                encounteredFatalError = true;
                fatalError = e;
            }

            StreamWriter file = new StreamWriter(outputFile);

            if (isValid && !encounteredFatalError)
                file.WriteLine("PASSED: Document is valid");
            else
                file.WriteLine("FAILED: Document is invalid");

            // Printing
            foreach (string entry in list)
            {
                file.WriteLine(entry);
            }
            if (encounteredFatalError)
            {
                file.WriteLine("Error: a FATAL error has occured " +
                        "while reading the file.\r\n" + fatalError.ToString());
            }
            file.Close();
        }
开发者ID:GerhardMaier,项目名称:COLLADA-CTS,代码行数:55,代码来源:SchemaValidate.cs

示例7: Page_Load

        private void Page_Load(object sender, System.EventArgs e)
        {
            XmlValidatingReader reader = null;
            XmlSchemaCollection myschema = new XmlSchemaCollection();
            ValidationEventHandler eventHandler = new ValidationEventHandler(ShowCompileErrors );
            try
            {

                String xmlFrag = @"<?xml version='1.0' ?>
                                                <item>
                                                <xxx:price xmlns:xxx='xxx' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
                                                xsi:schemaLocation='test.xsd'></xxx:price>
                                                </item>";
                    /*"<author xmlns='urn:bookstore-schema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" +
                                            "<first-name>Herman</first-name>" +
                                            "<last-name>Melville</last-name>" +
                                            "</author>";*/
                string xsd = @"<?xml version='1.0' encoding='UTF-8'?>
            <xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' targetNamespace='xxx'>
            <xsd:element name='price' type='xsd:integer' xsd:default='12'/>
            </xsd:schema>";

                //Create the XmlParserContext.
                XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);
                //Implement the reader.
                reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
                //Add the schema.
                myschema.Add("xxx", new XmlTextReader(new StringReader(xsd)));

                //Set the schema type and add the schema to the reader.
                reader.ValidationType = ValidationType.Schema;
                reader.Schemas.Add(myschema);
                while (reader.Read()){Response.Write(reader.Value);}
                Response.Write("<br>Completed validating xmlfragment<br>");
            }
            catch (XmlException XmlExp)
            {
                Response.Write(XmlExp.Message + "<br>");
            }

            catch(XmlSchemaException XmlSchExp)
            {
                Response.Write(XmlSchExp.Message + "<br>");
            }
            catch(Exception GenExp)
            {
                Response.Write(GenExp.Message + "<br>");
            }
            finally
            {}
            XmlDocument doc;
        }
开发者ID:rags,项目名称:playground,代码行数:52,代码来源:frmValidatingReader.aspx.cs

示例8: v2

        //[Variation(Desc = "v2 - Contains with not added schema")]
        public void v2()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
#pragma warning disable 0618
            XmlSchemaCollection scl = new XmlSchemaCollection();
#pragma warning restore 0618

            XmlSchema Schema = scl.Add(null, TestData._XsdAuthor);

            Assert.Equal(sc.Contains(Schema), false);

            return;
        }
开发者ID:geoffkizer,项目名称:corefx,代码行数:14,代码来源:TC_SchemaSet_Contains_schema.cs

示例9: Validate

        public void Validate(string strXMLDoc)
        {
            try
            {
                // Declare local objects
                XmlTextReader tr = null;
                XmlSchemaCollection xsc = null;
                XmlValidatingReader vr = null;

                // Text reader object
                tr = new XmlTextReader(Application.StartupPath + @"\BDOCImportSchema.xsd");
                xsc = new XmlSchemaCollection();
                xsc.Add(null, tr);

                // XML validator object

                vr = new XmlValidatingReader(strXMLDoc,
                             XmlNodeType.Document, null);

                vr.Schemas.Add(xsc);

                // Add validation event handler

                vr.ValidationType = ValidationType.Schema;
                vr.ValidationEventHandler +=
                         new ValidationEventHandler(ValidationHandler);

                // Validate XML data

                while (vr.Read()) ;

                vr.Close();

                // Raise exception, if XML validation fails
                if (ErrorsCount > 0)
                {
                    throw new Exception(ErrorMessage);
                }

                // XML Validation succeeded
                Console.WriteLine("XML validation succeeded.\r\n");
            }
            catch (Exception error)
            {
                // XML Validation failed
                Console.WriteLine("XML validation failed." + "\r\n" +
                "Error Message: " + error.Message);
                throw new Exception("Error in XSD verification:\r\n" + error.Message);
            }
        }
开发者ID:andresvela,项目名称:BDOCEXCEL2XML,代码行数:50,代码来源:XMLValidator.cs

示例10: ValidateXml

 public static void ValidateXml(Stream xmlStream, XmlSchema xsdSchema)
 {
     XmlTextReader reader1 = null;
       try
       {
     reader1 = new XmlTextReader(xmlStream);
     XmlSchemaCollection collection1 = new XmlSchemaCollection();
     collection1.Add(xsdSchema);
     XmlValidatingReader reader2 = new XmlValidatingReader(reader1);
     reader2.ValidationType = ValidationType.Schema;
     reader2.Schemas.Add(collection1);
     ArrayList list1 = new ArrayList();
     while (reader2.ReadState != ReadState.EndOfFile)
     {
       try
       {
     reader2.Read();
     continue;
       }
       catch (XmlSchemaException exception1)
       {
     list1.Add(exception1);
     continue;
       }
     }
     if (list1.Count != 0)
     {
       throw new XmlValidationException(list1);
     }
       }
       catch (XmlValidationException exception2)
       {
     throw exception2;
       }
       catch (Exception exception3)
       {
     throw new XmlValidationException(exception3.Message, exception3);
       }
       finally
       {
     if (reader1 != null)
     {
       reader1.Close();
     }
       }
 }
开发者ID:bmadarasz,项目名称:ndihelpdesk,代码行数:46,代码来源:XmlSchemaValidator.cs

示例11: SchemaValidator

			public SchemaValidator(string xmlFile, string schemaFile)
			{
				XmlSchemaCollection myXmlSchemaCollection = new XmlSchemaCollection();
				XmlTextReader xmlTextReader = new XmlTextReader(schemaFile);
				try
				{
					myXmlSchemaCollection.Add(XmlSchema.Read(xmlTextReader, null));
				}
				finally
				{
					xmlTextReader.Close();
				}

				// Validate the XML file with the schema
				XmlTextReader myXmlTextReader = new XmlTextReader (xmlFile);
				myXmlValidatingReader = new XmlValidatingReader(myXmlTextReader);
				myXmlValidatingReader.Schemas.Add(myXmlSchemaCollection);
				myXmlValidatingReader.ValidationType = ValidationType.Schema;
			}
开发者ID:Phaiax,项目名称:dotnetautoupdate,代码行数:19,代码来源:XmlTest.cs

示例12: PcaCompiler

        public PcaCompiler()
        {
            try
            {
                Assembly assembly =	Assembly.GetExecutingAssembly();

                // read	schema
                using (Stream s	= assembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.pubca.xsd"))
                {
                    this.xmlSchema = XmlSchema.Read(s, null);
                }

                // read	table definitions
                using (Stream s	= assembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Data.tables.xml"))
                {
                    XmlReader tableDefinitionsReader = new XmlTextReader(s);

            #if	DEBUG
                    Assembly wixAssembly = Assembly.GetAssembly(typeof(Compiler));
                    using (Stream schemaStream = wixAssembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.tables.xsd"))
                    {
                        XmlReader schemaReader = new XmlTextReader(schemaStream);
                        XmlSchemaCollection	schemas	= new XmlSchemaCollection();
                        schemas.Add("http://schemas.microsoft.com/wix/2003/04/tables", schemaReader);

                        XmlValidatingReader	validatingReader = new XmlValidatingReader(tableDefinitionsReader);
                        validatingReader.Schemas.Add(schemas);

                        tableDefinitionsReader = validatingReader;
                    }
            #endif

                    this.tableDefinitionCollection = TableDefinitionCollection.Load(tableDefinitionsReader);
                    tableDefinitionsReader.Close();
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                System.Console.WriteLine(e.ToString());
                throw;
            }
        }
开发者ID:sillsdev,项目名称:FwSupportTools,代码行数:43,代码来源:PcaCompiler.cs

示例13: NfeDadosMgs

        private void NfeDadosMgs()
        {
            StreamReader ler = null; ;
            XmlSchemaCollection myschema = new XmlSchemaCollection();
            XmlValidatingReader reader;
            string _ano = DateTime.Now.ToString("yy");
            _id = _cuf + _ano + _cnpj + _mod + _serie + _nnfini + _nnffim;         
            try
            {

                XDocument xDados = new XDocument(new XElement(pf + "inutNFe", new XAttribute("versao", _pversaoaplic),
                                                    new XElement(pf + "infInut", new XAttribute("Id", "ID" + _id),
                                                        new XElement(pf + "tpAmb", _tpamp),
                                                        new XElement(pf + "xServ", "INUTILIZAR"),
                                                        new XElement(pf + "cUF", _cuf),
                                                        new XElement(pf + "ano", DateTime.Now.ToString("yy")),
                                                        new XElement(pf + "CNPJ", _cnpj),
                                                        new XElement(pf + "mod", _mod),
                                                        new XElement(pf + "serie",  Convert.ToInt16(_serie)),
                                                        new XElement(pf + "nNFIni", Convert.ToInt32(_nnfini)),
                                                        new XElement(pf + "nNFFin", Convert.ToInt32(_nnffim)),
                                                        new XElement(pf + "xJust", _sjust))));

                xDados.Save(_spath + "\\" + _id + "_ped_inu.xml");
                 AssinaNFeInutXml assinaInuti = new AssinaNFeInutXml();
                assinaInuti.ConfigurarArquivo(_spath + "\\" + _id + "_ped_inu.xml", "infInut", cert);

                ler = File.OpenText(_spath + "\\" + _id + "_ped_inu.xml");

                XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);

                reader = new XmlValidatingReader(ler.ReadToEnd().ToString(), XmlNodeType.Element, context);

                myschema.Add("http://www.portalfiscal.inf.br/nfe", _sschema + "\\inutNFe_v2.00.xsd");

                reader.ValidationType = ValidationType.Schema;

                reader.Schemas.Add(myschema);

                while (reader.Read())
                { }

            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
            finally
            {
                ler.Close();
            }
        }
开发者ID:dramosti,项目名称:GeraXml_2.0,代码行数:53,代码来源:belNfeInutilizacao.cs

示例14: GetSchemas

        /// <summary>
        /// Get the schemas required to validate a library.
        /// </summary>
        /// <returns>The schemas required to validate a library.</returns>
        internal static XmlSchemaCollection GetSchemas()
        {
            if (null == Localization.schemas)
            {
                Assembly assembly = Assembly.GetExecutingAssembly();

                using (Stream localizationSchemaStream = assembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.wixloc.xsd"))
                {
                    schemas = new XmlSchemaCollection();
                    XmlSchema localizationSchema = XmlSchema.Read(localizationSchemaStream, null);
                    schemas.Add(localizationSchema);
                }
            }

            return schemas;
        }
开发者ID:Jeremiahf,项目名称:wix3,代码行数:20,代码来源:Localization.cs

示例15: InitializeTask

        /// <summary>
        /// Initializes the task and verifies parameters.
        /// </summary>
        /// <param name="TaskNode">Node that contains the XML fragment used to define this task instance.</param>
        protected override void InitializeTask(XmlNode TaskNode)
        {
            XmlElement taskXml = (XmlElement) TaskNode.Clone();

            // Expand all properties in the task and its child elements
            if (taskXml.ChildNodes != null) {
                ExpandPropertiesInNodes(taskXml.ChildNodes);
                if (taskXml.Attributes != null) {
                    foreach (XmlAttribute attr in taskXml.Attributes) {
                        attr.Value = Properties.ExpandProperties(attr.Value, Location);
                    }
                }
            }

            // Get the [SchemaValidator(type)] attribute
            SchemaValidatorAttribute[] taskValidators =
                (SchemaValidatorAttribute[])GetType().GetCustomAttributes(
                typeof(SchemaValidatorAttribute), true);

            if (taskValidators.Length > 0) {
                SchemaValidatorAttribute taskValidator = taskValidators[0];
                XmlSerializer taskSerializer = new XmlSerializer(taskValidator.ValidatorType);

                // get embedded schema resource stream
                Stream schemaStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    taskValidator.ValidatorType.Namespace);

                // ensure schema resource was embedded
                if (schemaStream == null) {
                    throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                        "Schema resource '{0}' could not be found.",
                        taskValidator.ValidatorType.Namespace), Location);
                }

                // load schema resource
                XmlTextReader tr = new XmlTextReader(
                    schemaStream, XmlNodeType.Element, null);

                // Add the schema to a schema collection
                XmlSchema schema = XmlSchema.Read(tr, null);
                XmlSchemaCollection schemas = new XmlSchemaCollection();
                schemas.Add(schema);

                string xmlNamespace = (taskValidator.XmlNamespace != null ? taskValidator.XmlNamespace : GetType().FullName);

                // Create a namespace manager with the schema's namespace
                NameTable nt = new NameTable();
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
                nsmgr.AddNamespace(string.Empty, xmlNamespace);

                // Create a textreader containing just the Task's Node
                XmlParserContext ctx = new XmlParserContext(
                    null, nsmgr, null, XmlSpace.None);
                taskXml.SetAttribute("xmlns", xmlNamespace);
                XmlTextReader textReader = new XmlTextReader(taskXml.OuterXml,
                    XmlNodeType.Element, ctx);

                // Copy the node from the TextReader and indent it (for error
                // reporting, since NAnt does not retain formatting during a load)
                StringWriter stringWriter = new StringWriter();
                XmlTextWriter textWriter = new XmlTextWriter(stringWriter);
                textWriter.Formatting = Formatting.Indented;

                textWriter.WriteNode(textReader, true);

                //textWriter.Close();
                XmlTextReader formattedTextReader = new XmlTextReader(
                    stringWriter.ToString(), XmlNodeType.Document, ctx);

                // Validate the Task's XML against its schema
                XmlValidatingReader validatingReader = new XmlValidatingReader(
                    formattedTextReader);
                validatingReader.ValidationType = ValidationType.Schema;
                validatingReader.Schemas.Add(schemas);
                validatingReader.ValidationEventHandler +=
                    new ValidationEventHandler(Task_OnSchemaValidate);

                while (validatingReader.Read()) {
                    // Read strictly for validation purposes
                }
                validatingReader.Close();

                if (!_validated) {
                    // Log any validation errors that have ocurred
                    for (int i = 0; i < _validationExceptions.Count; i++) {
                        BuildException ve = (BuildException) _validationExceptions[i];
                        if (i == _validationExceptions.Count - 1) {
                            // If this is the last validation error, throw it
                            throw ve;
                        }
                        Log(Level.Info, ve.Message);
                    }
                }

                NameTable taskNameTable = new NameTable();
                XmlNamespaceManager taskNSMgr = new XmlNamespaceManager(taskNameTable);
//.........这里部分代码省略.........
开发者ID:vardars,项目名称:ci-factory,代码行数:101,代码来源:SchemaValidatedTask.cs


注:本文中的System.Xml.Schema.XmlSchemaCollection.Add方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。