• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            C++ Programmer's Cookbook

            {C++ 基礎(chǔ)} {C++ 高級} {C#界面,C++核心算法} {設(shè)計(jì)模式} {C#基礎(chǔ)}

            Validate an XML Document Against a Schema(XML 三)

            Solution

            Use the System.Xml.XmlValidatingReader class. Create an instance, load a schema into the XmlValidatingReader.Schemas collection, and then move through the document one node at a time by calling XmlValidatingReader.Read, catching any validation exceptions. To find all the errors in a document without catching exceptions, handle the ValidationEventHandler event.


            Here's the complete schema for the product catalog XML:

            <?xml version="1.0"?>
            <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            
               <!-- Define the complex type product. -->
               <xsd:complexType name="product">
                  <xsd:sequence>
                     <xsd:element name="productName" type="xsd:string"/>
                     <xsd:element name="productPrice" type="xsd:decimal"/>
                     <xsd:element name="inStock" type="xsd:boolean"/>
                  </xsd:sequence>
                  <xsd:attribute name="id" type="xsd:integer"/>
               </xsd:complexType>
            
               <!-- This is the structure the document must match.
                    It begins with a productCatalog element that nests other elements. -->
               <xsd:element name="productCatalog">
                  <xsd:complexType>
                     <xsd:sequence>
                        <xsd:element name="catalogName" type="xsd:string"/>
                        <xsd:element name="expiryDate" type="xsd:date"/>
            
                        <xsd:element name="products">
                           <xsd:complexType>
                              <xsd:sequence>
                                 <xsd:element name="product" type="product"
                                  maxOccurs="unbounded" />
                              </xsd:sequence>
                           </xsd:complexType>
                        </xsd:element>
                     </xsd:sequence>
                  </xsd:complexType>
               </xsd:element>
            

            </xsd:schema>






            <?xml version="1.0" ?>
            <productCatalog>
                <catalogName>Acme Fall 2003 Catalog</catalogName>
                <expiryDate>Jan 1, 2004</expiryDate>
            
                <products>
                    <product id="1001">
                        <productName>Magic Ring</productName>
                        <productPrice>$342.10</productPrice>
                        <inStock>true</inStock>
                    </product>
                    <product id="1002">
                        <productName>Flying Carpet</productName>
                        <productPrice>982.99</productPrice>
                        <inStock>Yes</inStock>
                    </product>
                </products>
            </productCatalog>

            The next example shows a utility class that displays all errors in an XML document when the
            ValidateXml method is called. Errors are displayed in a console window, and a final Boolean
            variable is returned to indicate the success or failure of the entire validation operation.

            using System;
            using System.Xml;
            using System.Xml.Schema;
            
            public class ConsoleValidator {
            
                // Set to true if at least one error exists.
                private bool failed;
            
                public bool Failed {
                    get {return failed;}
                }
            
                public bool ValidateXml(string xmlFilename, string schemaFilename) {
            
                    // Create the validator.
                    XmlTextReader r = new XmlTextReader(xmlFilename);
                    XmlValidatingReader validator = new XmlValidatingReader(r);
                    validator.ValidationType = ValidationType.Schema;
            
                    // Load the schema file into the validator.
                    XmlSchemaCollection schemas = new XmlSchemaCollection();
                    schemas.Add(null, schemaFilename);
                    validator.Schemas.Add(schemas);
            
                    // Set the validation event handler.
                    validator.ValidationEventHandler += 
                      new ValidationEventHandler(ValidationEventHandler);
                        
                    failed = false;
                    try {
            
                        // Read all XML data.
                        while (validator.Read())
                        {}
                    }catch (XmlException err) {
            
                        // This happens if the XML document includes illegal characters
                        // or tags that aren't properly nested or closed.
                        Console.WriteLine("A critical XML error has occurred.");
                        Console.WriteLine(err.Message);
                        failed = true;
                    }finally {
                        validator.Close();
                    }
            
                    return !failed;
                }
            
                private void ValidationEventHandler(object sender, 
                  ValidationEventArgs args) {
            
                    failed = true;
            
                    // Display the validation error.
                    Console.WriteLine("Validation error: " + args.Message);
                    Console.WriteLine();
                }
            }

            Here's how you would use the class to validate the product catalog:

            using System;
            
            public class ValidateXml {
            
                private static void Main() {
            
                    ConsoleValidator consoleValidator = new ConsoleValidator();
                    Console.WriteLine("Validating ProductCatalog.xml.");
            
                    bool success = consoleValidator.ValidateXml("ProductCatalog.xml",
                      "ProductCatalog.xsd");
                    if (!success) {
                        Console.WriteLine("Validation failed.");
                    }else {
                        Console.WriteLine("Validation succeeded.");
                    }
            
                    Console.ReadLine();
                }
            }


            the result:
            Validating ProductCatalog_Invalid.xml.
            
            Validation error: The 'expiryDate' element has an invalid value according to
             its data type. [path information truncated] 
            
            Validation error: The 'productPrice' element has an invalid value according to
             its data type. [path information truncated]
            
            Validation error: The 'inStock' element has an invalid value according to its
             data type. [path information truncated]
            
            Validation failed.


            Finally, if you want to validate an XML document and then process it, you can use
            XmlValidatingReader
            to scan a document as it's read into an in-memory XmlDocument.
            Here's how it works:

            XmlDocument doc = new XmlDocument();
            XmlTextReader r = new XmlTextReader("ProductCatalog.xml");
            XmlValidatingReader validator = new XmlValidatingReader(r);
            
            // Load the schema into the validator.
            validator.ValidationType = ValidationType.Schema;
            XmlSchemaCollection schemas = new XmlSchemaCollection();
            schemas.Add(null, "ProductCatalog.xsd");
            validator.Schemas.Add(schemas);
            
            // Load the document and validate it at the same time.
            // Don't handle the ValidationEventHandler event. Instead, allow any errors
            /// to be thrown as an XmlSchemaException.
            try {
                doc.Load(validator);
                // (Validation succeeded if you reach here.)
            }catch (XmlSchemaException err) {
                // (Validation failed if you reach here.)
            }







            posted on 2005-11-23 18:26 夢在天涯 閱讀(958) 評論(0)  編輯 收藏 引用 所屬分類: C#/.NET

            公告

            EMail:itech001#126.com

            導(dǎo)航

            統(tǒng)計(jì)

            • 隨筆 - 461
            • 文章 - 4
            • 評論 - 746
            • 引用 - 0

            常用鏈接

            隨筆分類

            隨筆檔案

            收藏夾

            Blogs

            c#(csharp)

            C++(cpp)

            Enlish

            Forums(bbs)

            My self

            Often go

            Useful Webs

            Xml/Uml/html

            搜索

            •  

            積分與排名

            • 積分 - 1804430
            • 排名 - 5

            最新評論

            閱讀排行榜

            亚洲人成电影网站久久| 国产情侣久久久久aⅴ免费| 久久久久久综合一区中文字幕 | 久久久久久久亚洲Av无码| 九九久久精品国产| 精品多毛少妇人妻AV免费久久| 久久精品人人做人人爽97| 超级碰碰碰碰97久久久久| 久久受www免费人成_看片中文| 欧美与黑人午夜性猛交久久久| 久久免费大片| 亚洲AⅤ优女AV综合久久久| 欧美久久亚洲精品| 久久只有这里有精品4| 色综合久久夜色精品国产| 亚洲中文字幕无码久久2017| 久久久久久国产精品美女| 色偷偷88888欧美精品久久久 | 精品亚洲综合久久中文字幕| 国产精品久久成人影院| 亚洲精品国产成人99久久| 久久天天躁狠狠躁夜夜2020 | 欧美日韩精品久久久免费观看| 久久久久se色偷偷亚洲精品av| 亚洲中文字幕无码一久久区| 久久中文骚妇内射| 国产叼嘿久久精品久久| 久久国产三级无码一区二区| 18禁黄久久久AAA片| 国产精品岛国久久久久| 久久久久亚洲AV成人网| 久久国语露脸国产精品电影| 成人妇女免费播放久久久| 久久精品二区| 久久99国产综合精品女同| 久久精品国产WWW456C0M| 色综合久久久久综合体桃花网 | 久久久久国产成人精品亚洲午夜| 狠狠色丁香久久婷婷综合蜜芽五月| 国产婷婷成人久久Av免费高清| 久久久久无码中|