The C # code is as follows:
voidMain () {stringerrormessage; Validatexml (@"C:\Tarena\Backup\ Database \xml\book.xml",@"C:\Tarena\Backup\ Database \xml\book.xsd", outerrormessage). Dump (); Errormessage.dump ();}//Define Other methods and classes hereStatic BOOLValidatexml (stringXMLFile,stringSchemafile, out stringerrormessage) { BOOLIsValid =true;//Validation Results Try{XmlSchemaSet Schemaset=NewXmlSchemaSet (); Schemaset.add (NULL, schemafile);//Add schema validation filexmlreadersettings readersetting=Newxmlreadersettings (); Readersetting.validationtype= ValidationType.Schema;//Configuring authentication MethodsReadersetting.schemas=Schemaset; using(XmlReader XmlReader =xmlreader.create (xmlfile, readersetting)) { while(Xmlreader.read ()) {}} errormessage=string. Empty; } Catch(Exception ex) {IsValid=false; ErrorMessage=Ex. Message; } returnIsValid;}
where the XML file
<?XML version= "1.0" encoding= "Utf-8"?><Booksxmlns= "Http://www.w3.org/2001/XMLSchema"> < BookID= "1"> <title>Journey</title> <author>Wu Chengen</author> < Price>10.99</ Price> <pubdate>2010-01-01</pubdate> <category>Literature Category</category> </ Book> < BookID= "2"> <title>Three kingdoms</title> <author>Luo Guan Zhong</author> < Price>20.99</ Price> <pubdate>2010-02-01</pubdate> <category>Literature Category</category> </ Book> < BookID= "3"> <title>Dream</title> <author>Cao Xueqin</author> < Price>30.99</ Price> <pubdate>2010-03-01</pubdate> <category>Literature Category</category> </ Book> < BookID= "4"> <title>Outlaws</title> <author>Shi Naian</author> < Price>40.99</ Price> <pubdate>2010-04-01</pubdate> <category>Literature Category</category> </ Book></Books>
Validation file (Schema)
<?XML version= "1.0" encoding= "Utf-8"?><Xs:schemaattributeFormDefault= "unqualified"elementFormDefault= "qualified"targetnamespace= "Book.xsd"Xmlns:xs= "Http://www.w3.org/2001/XMLSchema"> <xs:elementname= "Books"> <Xs:complextype> <xs:sequence> <xs:elementmaxOccurs= "unbounded"name= "book"> <Xs:complextype> <xs:sequence> <xs:elementname= "title"type= "Xs:string" /> <xs:elementname= "Author"type= "Xs:string" /> <xs:elementname= "Price"type= "Xs:decimal" /> <xs:elementname= "pubdate"type= "Xs:date" /> </xs:sequence> </Xs:complextype> </xs:element> </xs:sequence> </Xs:complextype> </xs:element></Xs:schema>
To use C # to invoke the schema file to validate an XML document