← Tutti gli articoli

XSD Schema Validation

08 May 2012  ·  C# · Article  ·  490 visite

Xml document conforms to a particular pattern: XSD

XSD (short for XML Schema Definition)


You can validate an XML file or document against one or more schemas before reading or processing it. There are a number of reasons to do so: You can get away with less error checking and exception handling. Schema validation picks up errors you might otherwise overlook. Error messages are detailed and informative. To perform validation, plug a schema into an XmlReader, an XmlDocument, or an X-DOM object, and then read or load the XML as you would normally. Schema validation happens automatically as content is read, so the input stream is not read twice.
 
Supposing you have the following schema validation:
 
customers.xsd
  1. <? xml   version = "1.0"   encoding = "utf-8"   ?>   
  2. < xs:schema   attributeFormDefault = "unqualified"   
  3.            elementFormDefault="qualified"  
  4.            xmlns:xs="http://www.w3.org/2001/XMLSchema">  
  5. < xs:element   name = "customers" >   
  6.   <xs:complexType>  
  7.     <xs:sequence>  
  8.       <xs:element name="customer" minOccurs="0" maxOccurs="unbounded">  
  9.         <xs:complexType>  
  10.           <xs:attribute name="name" type="xs:string" use="required" />  
  11.           <xs:attribute name="city" type="xs:string" use="required" />  
  12.           <xs:attribute name="country">  
  13.             <xs:simpleType>  
  14.               <xs:restriction base="xs:string">  
  15.                 <xs:enumeration value="Italy" />  
  16.                 <xs:enumeration value="USA" />  
  17.               </xs:restriction>  
  18.             </xs:simpleType>  
  19.           </xs:attribute>  
  20.         </xs:complexType>  
  21.       </xs:element>  
  22.     </xs:sequence>  
  23.   </xs:complexType>  
  24. </ xs:element >   
  25. </ xs:schema >   

 You have to validate the following xml file:
 
customerswithorders.xml
 
  1. <? xml   version = "1.0"   encoding = "utf-8" ?>   
  2. < customers >   
  3. < customer   name = "Paolo"   city = "Brescia"   country = "Italy" >   
  4.     <orders>  
  5.       <order id="1" idProduct="1" quantity="3" shipped="false" month="January" />  
  6.       <order id="2" idProduct="2" quantity="5" shipped="true" month="May" />  
  7.     </orders>  
  8.   </customer>  
  9.   <customer name="Marco" city="Torino" country="Italy">  
  10.     <orders>  
  11.       <order id="3" idProduct="1" quantity="10" shipped="false" month="July" />  
  12.       <order id="4" idProduct="3" quantity="20" shipped="true" month="December" />  
  13.     </orders>  
  14.   </customer>  
  15.   
  16.   
  17.   <customer name="Paolo" city="Brescia" country="Italy2">  
  18.     <orders>  
  19.       <order id="1" idProduct="1" quantity="3" shipped="false" month="January" />  
  20.       <order id="2" idProduct="2" quantity="5" shipped="true" month="May" />  
  21.     </orders>  
  22.   </customer>  
  23. </ customers >   
 
 
Solution:
 
 
  1. private void button5_Click(object sender, EventArgs e)  
  2. {  
  3.     string apppath = Path.GetDirectoryName(Application.ExecutablePath);  
  4.   
  5.   
  6.   
  7.      // xml file path  
  8.      string filename = apppath + @"\customerswithorders.xml";  
  9.      // xsd file path  
  10.      string fileSchema = apppath + @"\xsd\customers.xsd";  
  11.   
  12.      // reader settings  
  13.      XmlReaderSettings settings = new XmlReaderSettings();  
  14.      settings.ValidationType = ValidationType.Schema;  
  15.      //settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;  
  16.      settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;  
  17.   
  18.      settings.Schemas.Add(null, fileSchema);  
  19.      settings.ValidationType = ValidationType.Schema;  
  20.      settings.ValidationEventHandler += new ValidationEventHandler(XmlValidationError);  
  21.   
  22.      // validation  
  23.      using (XmlReader reader = XmlReader.Create(filename, settings))  
  24.      {  
  25.          while (reader.Read()) ;  
  26.      }  
  27.   
  28.      MessageBox.Show("Validation finished",  
  29.        "Information",  
  30.        MessageBoxButtons.OK,  
  31.        MessageBoxIcon.Information);  
  32.   
  33.   
  34.   
  35. }  
  36.   
  37. private  void ValidationCallBack(object sender, ValidationEventArgs e)  
  38. {  
  39.     validation = false;  
  40.     //Console.WriteLine("Validation Error: {0}", e.Message);  
  41.     listBox1.Items.Add(e.Message);  
  42. }  
  43.   
  44.   
  45. static void XmlValidationError(object sender, ValidationEventArgs e)  
  46. {  
  47.     MessageBox.Show(e.Message,  
  48.       e.Severity.ToString(),  
  49.       MessageBoxButtons.OK,  
  50.       e.Severity == XmlSeverityType.Warning ?  
  51.       MessageBoxIcon.Warning  
  52.       : MessageBoxIcon.Error);  
  53. }  
Si è verificato un errore imprevisto. Ricarica

Rejoining the server...

Rejoin failed... trying again in seconds.

Failed to rejoin.
Please retry or reload the page.

The session has been paused by the server.

Failed to resume the session.
Please retry or reload the page.