XML documents can reference optional documents that specify how the XML documents should be structured. These optional documents called Documents Type Definitions (DTDs) and Schemas.
It uses the extension .xdr (XML-Data Reduced) you can check the attached files for the this Schema syntax, it is an xml document, but has special elements and attributes.
It uses the extension .xsd (XML Schema Definitions) also it is an XML Document with special elements.
Using this Schema file you can validate your XML file to make sure it fits to your application's needs and validate the inputs in order to prevent any exception in your code.
The .Net framework gives you all the tools you need so that you can build XSD schemas and also validate them.
First, let's see how can we create a schema using XSD.exe file (It comes with Visual Studio):
The XML Schema Definition tool generates XML schema or common language runtime classes from XDR, XML, and XSD files, or from classes in a runtime assembly.The following command generates an XML schema from myFile.xml and saves it to the specified directory xsd myFile.xml /outputdir:myOutputDirConsider that we have the following xml data file EmployeeList.xml:<EmployeeList> <Company ID="1"> <Employee>Employee11Employee> <Employee>Employee12Employee> <Employee>Employee13Employee> Company> <Company ID="2"> <Employee>Employee21Employee> <Employee>Employee22Employee> <Employee>Employee23Employee> Company> <Company ID="3"> <Employee>Employee31Employee> <Employee>Employee32Employee> <Employee>Employee33Employee> <Employee>Employee34Employee> Company>EmployeeList>Now, execute XSD.exe on the xml data file:> XSD EmployeeList.xmlThe result xsd file EmployeeList.xsd will be :xml version="1.0" encoding="utf-8"?><xs:schema id="EmployeeList" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="EmployeeList" msdata:IsDataSet="true" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="Company"> <xs:complexType> <xs:sequence> <xs:element name="Employee" nillable="true" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:simpleContent msdata:ColumnName="Employee_Text" msdata:Ordinal="0"> <xs:extension base="xs:string"> xs:extension> xs:simpleContent> xs:complexType> xs:element> xs:sequence> <xs:attribute name="ID" type="xs:string" /> xs:complexType> xs:element> xs:choice> xs:complexType> xs:element>xs:schema>
The XML Schema Definition tool generates XML schema or common language runtime classes from XDR, XML, and XSD files, or from classes in a runtime assembly.
The following command generates an XML schema from myFile.xml and saves it to the specified directory
myFile.xml
xsd myFile.xml /outputdir:myOutputDir
Consider that we have the following xml data file EmployeeList.xml:
<EmployeeList> <Company ID="1"> <Employee>Employee11Employee> <Employee>Employee12Employee> <Employee>Employee13Employee> Company> <Company ID="2"> <Employee>Employee21Employee> <Employee>Employee22Employee> <Employee>Employee23Employee> Company> <Company ID="3"> <Employee>Employee31Employee> <Employee>Employee32Employee> <Employee>Employee33Employee> <Employee>Employee34Employee> Company>EmployeeList>
Now, execute XSD.exe on the xml data file:
The result xsd file EmployeeList.xsd will be :
Second, now that we have our Schema let's see the steps that we need to do in order to validate against our schema (.NET 2.0):
1. Read the XML file content as Stream, TextReader or XmlReader.2. Read the Schema file content as Stream, TextReader or XmlReader.3. Create a new instance of XmlSchema object.4. Set XmlSchema object by calling XmlSchema.Read() method and passing the content of Schema file and ValidationEventHandler method address to it.5. Create a new instance of XmlReaderSettings object.6. Set ValidationType for XmlReaderSettings object to Schema.7. Add your XmlSchema object to XmlReaderSettings Schemas collection by calling its Schemas.Add() method.8. Add your ValidationEventHandler method address to XmlValidationReader's ValidationEventHandler handler.9. Create a new instance of XmlReader object and pass your XML file content (as Stream or a Reader object) and XmlReaderSettings object to it.10. Call Read() method of the Reader or Stream object to contain your XML file content in a loop to parse and validate it completely.11. Add your logic to ValidationEventHandler method you created to implement what you want to be done in the validation process.Here is the code to accomplish this:private void ValidatingProcess(string XSDPath, string XMLPath){ try { // 1- Read XML file content this.Reader = new XmlTextReader(XMLPath); // 2- Read Schema file content StreamReader SR = new StreamReader(XSDPath); // 3- Create a new instance of XmlSchema object XmlSchema Schema = new XmlSchema(); // 4- Set Schema object by calling XmlSchema.Read() method Schema = XmlSchema.Read(SR, new ValidationEventHandler(ReaderSettings_ValidationEventHandler)); // 5- Create a new instance of XmlReaderSettings object XmlReaderSettings ReaderSettings = new XmlReaderSettings(); // 6- Set ValidationType for XmlReaderSettings object ReaderSettings.ValidationType = ValidationType.Schema; // 7- Add Schema to XmlReaderSettings Schemas collection ReaderSettings.Schemas.Add(Schema); // 8- Add your ValidationEventHandler address to // XmlReaderSettings ValidationEventHandler ReaderSettings.ValidationEventHandler += new ValidationEventHandler(ReaderSettings_ValidationEventHandler); // 9- Create a new instance of XmlReader object XmlReader objXmlReader = XmlReader.Create(Reader, ReaderSettings); // 10- Read XML content in a loop while (objXmlReader.Read()) { /*Empty loop*/} }//try // Handle exceptions if you want catch (UnauthorizedAccessException AccessEx) { throw AccessEx; }//catch catch (Exception Ex) { throw Ex; }//catch} private void ReaderSettings_ValidationEventHandler(object sender, ValidationEventArgs args){ // 11- Implement your logic for each validation iteration string strTemp; strTemp = "Line: " + this.Reader.LineNumber + " - Position: " + this.Reader.LinePosition + " - " + args.Message; this.Results.Add(strTemp);}
1. Read the XML file content as Stream, TextReader or XmlReader.
2. Read the Schema file content as Stream, TextReader or XmlReader.
3. Create a new instance of XmlSchema object.
4. Set XmlSchema object by calling XmlSchema.Read() method and passing the content of Schema file and ValidationEventHandler method address to it.
5. Create a new instance of XmlReaderSettings object.
6. Set ValidationType for XmlReaderSettings object to Schema.
7. Add your XmlSchema object to XmlReaderSettings Schemas collection by calling its Schemas.Add() method.
8. Add your ValidationEventHandler method address to XmlValidationReader's ValidationEventHandler handler.
9. Create a new instance of XmlReader object and pass your XML file content (as Stream or a Reader object) and XmlReaderSettings object to it.
10. Call Read() method of the Reader or Stream object to contain your XML file content in a loop to parse and validate it completely.
11. Add your logic to ValidationEventHandler method you created to implement what you want to be done in the validation process.
Here is the code to accomplish this:
private void ValidatingProcess(string XSDPath, string XMLPath){ try { // 1- Read XML file content this.Reader = new XmlTextReader(XMLPath); // 2- Read Schema file content StreamReader SR = new StreamReader(XSDPath); // 3- Create a new instance of XmlSchema object XmlSchema Schema = new XmlSchema(); // 4- Set Schema object by calling XmlSchema.Read() method Schema = XmlSchema.Read(SR, new ValidationEventHandler(ReaderSettings_ValidationEventHandler)); // 5- Create a new instance of XmlReaderSettings object XmlReaderSettings ReaderSettings = new XmlReaderSettings(); // 6- Set ValidationType for XmlReaderSettings object ReaderSettings.ValidationType = ValidationType.Schema; // 7- Add Schema to XmlReaderSettings Schemas collection ReaderSettings.Schemas.Add(Schema); // 8- Add your ValidationEventHandler address to // XmlReaderSettings ValidationEventHandler ReaderSettings.ValidationEventHandler += new ValidationEventHandler(ReaderSettings_ValidationEventHandler); // 9- Create a new instance of XmlReader object XmlReader objXmlReader = XmlReader.Create(Reader, ReaderSettings); // 10- Read XML content in a loop while (objXmlReader.Read()) { /*Empty loop*/} }//try // Handle exceptions if you want catch (UnauthorizedAccessException AccessEx) { throw AccessEx; }//catch catch (Exception Ex) { throw Ex; }//catch} private void ReaderSettings_ValidationEventHandler(object sender, ValidationEventArgs args){ // 11- Implement your logic for each validation iteration string strTemp; strTemp = "Line: " + this.Reader.LineNumber + " - Position: " + this.Reader.LinePosition + " - " + args.Message; this.Results.Add(strTemp);}
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.