How To Validate XML Using XSD In C#

Introduction

In this article, we will see how we can validate a given XML by using XML Schema (XSD). Sometimes, it needs to be validated at the business level. After reading this article, we can learn the below points.

  1. What is XML?
  2. What is XML Schema (XSD)?
  3. Why is it necessary to validate XML?
  4. How to validate XML?

What is XML?

Extensible Markup Language (XML) is used to describe the data. The XML standard is a flexible way to create information formats and electronically share structured data via the public Internet, as well as via corporate networks. The XML tags are not pre-defined in XML. You will have to create tags according to your needs.

Example – See below.

What is XML Schema (XSD)?

The XML Schema language is also referred to as XML Schema Definition (XSD). An XML Schema describes the structure of an XML document.

XSD is a schema language; you use it to define the possible structure and contents of an XML format. A validating parser can then check whether an XML instance document conforms to an XSD schema or a set of schemas.

Why is it necessary to validate XML?

When sending data from a sender to a receiver, it is essential that both parts have the same "expectations" about the content.

With XML Schemas, the sender can describe the data in a way that the receiver will understand.

How to validate XML?

We can validate XML using XSD schema file. Please see below steps and code.

Let’s create C# solution to validate XML data,

  1. Create console application. Steps – File-New - Project and give appropriate name for example – ValidateXML

    XSD in C#
  1. Let’s Add XML. Steps – Right click on Solution file - Add New Item - XML File.

    XSD in C#
  1. XML File looks as below,

    XSD in C#
  1. How to create XSD,
    • Open the existing XML.
    • Go to XML menu.
    • Select "Create schema" option.
    • Your XSD will be created automatically.

      XSD in C#

XSD File

This is an automatically created file; we have modified this XSD, as per our requirement.

  1. <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">  
  2.     <xs:element name="EmployeeDetails">  
  3.         <xs:complexType>  
  4.             <xs:sequence>  
  5.                 <xs:element name="FirstName" type="xs:string" />  
  6.                 <xs:element name="MiddleName" />  
  7.                 <xs:element name="LastName" type="xs:string" />  
  8.                 <xs:element name="EmailId" type="xs:string" />  
  9.                 <xs:element name="Mobile" type="xs:integer" />  
  10.                 <xs:element name="Address" type="xs:string" /> </xs:sequence>  
  11.         </xs:complexType>  
  12.     </xs:element>  
  13. </xs:schema>  

Modified XSD

  1. <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">  
  2.     <xs:element name="EmployeeDetails">  
  3.         <xs:complexType>  
  4.             <xs:sequence>  
  5.                 <xs:element name="FirstName" type="xs:string" />  
  6.                 <xs:element name="MiddleName">  
  7.                     <xs:simpleType>  
  8.                         <xs:restriction base="xs:string">  
  9.                             <xs:minLength value="1" /> </xs:restriction>  
  10.                     </xs:simpleType>  
  11.                 </xs:element>  
  12.                 <xs:element name="LastName" type="xs:string" />  
  13.                 <xs:element name="EmailId" type="xs:string" />  
  14.                 <xs:element name="Mobile" type="xs:integer" />  
  15.                 <xs:element name="Address">  
  16.                     <xs:simpleType>  
  17.                         <xs:restriction base="xs:string">  
  18.                             <xs:minLength value="5" />  
  19.                             <xs:maxLength value="100" /> </xs:restriction>  
  20.                     </xs:simpleType>  
  21.                 </xs:element>  
  22.                 <xs:element name="Car">  
  23.                     <xs:simpleType>  
  24.                         <xs:restriction base="xs:string">  
  25.                             <xs:enumeration value="Audi" />  
  26.                             <xs:enumeration value="Golf" />  
  27.                             <xs:enumeration value="BMW" /> </xs:restriction>  
  28.                     </xs:simpleType>  
  29.                 </xs:element>  
  30.             </xs:sequence>  
  31.         </xs:complexType>  
  32.     </xs:element>  
  33. </xs:schema>  

Validation description applied to the XSD.

Element Name Validation XSD Parameter
FirstName datatype as string  type="xs:string"
MiddleName datatype as string
Restricted maxlengt up to 1
 type="xs:string"
<xs:minLength value="1"/>
LastName datatype as string  type="xs:string"
EmailId datatype as string  type="xs:string"
Mobile datatype as integer type="xs:integer"
Address datatype as string
Restricted Min and Max length
 type="xs:string"
 <xs:minLength value="5"/>
<xs:maxLength value="100"/>
Car datatype as string
Value Should be Audi, Golf, BMW
 type="xs:string"
<xs:enumeration value="Audi"/>
<xs:enumeration value="Golf"/>
<xs:enumeration value="BMW"/>

So, let’s validate our XML by using the above XSD file.
  1. static void Main(string[] args) {  
  2.     var path = new Uri(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).LocalPath;  
  3.     XmlSchemaSet schema = new XmlSchemaSet();  
  4.     schema.Add("", path + "\\input.xsd");  
  5.     XmlReader rd = XmlReader.Create(path + "\\input.xml");  
  6.     XDocument doc = XDocument.Load(rd);  
  7.     doc.Validate(schema, ValidationEventHandler);  
  8. }  
  9. static void ValidationEventHandler(object sender, ValidationEventArgs e) {  
  10.     XmlSeverityType type = XmlSeverityType.Warning;  
  11.     if (Enum.TryParse < XmlSeverityType > ("Error", out type)) {  
  12.         if (type == XmlSeverityType.Error) throw new Exception(e.Message);  
  13.     }  
  14. }  
XSD in C#

Output

Success

Conclusion

I hope this article gave you a good idea of the validation of XML. Please download the attached code file. Thanks for reading this article. Please share your valuable feedback and comments.