Introduction
In this article, I will discuss about validating XML against defined XSD. Prior to getting into this article, it is mandatory that one should have basic knowledge on what is XML and XSD.
This article describes the below items:
- XML data validation with XSD like XML TAGS provided are present and appropriate with respect to XSD
- How to write custom validations like check to see email ID is valid or not
- How to generate XSD from XML
- How to generate Custom Error, when XML data validation fails
- How to write regular expression in XSD
Let's get into a sample with the below steps:
- Step 1: Define XML
- Step 2: Generate/Define XSD
- Step 3: Write code to validate XML with XSD
- Step 4: Handle Exception in by defining Custom Exception
Step 1: First define XML as follows & name XML file as Complex.XML
<Person xmlns:ns0="http://Testing.Message">
<Name>Surya Prakash</Name>
<Address>Malkajgiri</Address>
<Phone>9966537965</Phone>
<Email>suryaprakasash.bg@gmail.com</Email>
</Person>
Step 2: How to generate XSD? Simply follow the below steps
- Open Complex.XML file -> Go to VS Menu -> XML -> Create Schema, this will generate XSD as below:
="1.0"="utf-8"
<xs:schema xmlns:ns0="http://Testing.Message" attributeFormDefault="unqualified"
elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Person">
<xs:complexType>
<xs:sequence>
<xs:element name="Name" type="xs:string" />
<xs:element name="Address" type="xs:string" />
<xs:element name="Phone" type="xs:unsignedLong" />
<xs:element name="Email" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
- As we need to write code to check if Email ID is valid or not, we can do this by regular expression, by changing
EMAIL
tag type from String
to Custom Type as follows:
<xs:element name="Email" type="ValidateEmail" />
- As we have defined custom type, we need to define its structure as follows:
<xs:simpleType name="ValidateEmail">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Za-z0-9_]+([-+.'][A-Za-z0-9_]+)
*@[A-Za-z0-9_]+([-.][A-Za-z0-9_]+)*\.[A-Za-z0-9_]+([-.][A-Za-z0-9_]+)*" />
</xs:restriction>
</xs:simpleType>
- Finally our XSD file will be as:
="1.0"="utf-8"
<xs:schema xmlns:ns0="http://Testing.Message" attributeFormDefault="unqualified"
elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Person">
<xs:complexType>
<xs:sequence>
<xs:element name="Name" type="xs:string" />
<xs:element name="Address" type="xs:string" />
<xs:element name="Phone" type="xs:string" />
<xs:element name="Email" type="ValidateEmail" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:simpleType name="ValidateEmail">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Za-z0-9_]+([-+.'][A-Za-z0-9_]+)
*@[A-Za-z0-9_]+([-.][A-Za-z0-9_]+)*\.[A-Za-z0-9_]+([-.][A-Za-z0-9_]+)*" />
</xs:restriction>
</xs:simpleType>
</xs:schema>
Step 3: Create a new page as “Complex.aspx” and add a label to form by naming it as “lblMsg”
- Go to Complex.aspx.cs and define class level global variable as:
private int nErrors = 0;
private string strErrorMsg = string.Empty;
public string Errors { get { return strErrorMsg; } }
- Go to
Pageload
event of Complex.aspx page:
if (!IsValidXml(@"D:\Surya Prakash\WorkAround\GopalSample\XML\Complex.xml",
@"D:\Surya Prakash\WorkAround\GopalSample\XML\Complex.xsd"))
lblMsg.Text = Errors;
else
lblMsg.Text = string.Format("Success");
IsValidXML
function definition:
public bool IsValidXml(string xmlPath, string xsdPath)
{
bool bStatus = false;
try
{
XmlReaderSettings rs = new XmlReaderSettings();
rs.ValidationType = ValidationType.Schema;
rs.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation |
XmlSchemaValidationFlags.ReportValidationWarnings;
rs.ValidationEventHandler +=
new ValidationEventHandler(ValidationEventHandler);
rs.Schemas.Add(null, XmlReader.Create(xsdPath));
using (XmlReader xmlValidatingReader = XmlReader.Create(xmlPath, rs))
{ while (xmlValidatingReader.Read()) { } }
if (nErrors > 0) { throw new Exception(strErrorMsg); }
else { bStatus = true; }
}
catch (Exception error) { bStatus = false; }
return bStatus;
}
EventHandler
body definition for handling any exception:
void ValidationEventHandler(object sender, ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Warning) strErrorMsg += "WARNING: ";
else strErrorMsg += "ERROR: ";
nErrors++;
if (e.Exception.Message.Contains("'Email' element is invalid"))
{
strErrorMsg = strErrorMsg + getErrorString
("Provided Email data is Invalid", "CAPIEMAIL007") + "\r\n";
}
if (e.Exception.Message.Contains
("The element 'Person' has invalid child element"))
{
strErrorMsg = strErrorMsg + getErrorString
("Provided XML contains invalid child element",
"CAPINVALID005") + "\r\n";
}
else
{
strErrorMsg = strErrorMsg + e.Exception.Message + "\r\n";
}
}
Step 4: getErrorString: Custom error generation in XML string format
string getErrorString(string erroString, string errorCode)
{
StringBuilder errXMl = new StringBuilder();
errXMl.Append("<MyError> <errorString> ERROR_STRING </errorString>
<errorCode> ERROR_CODE </errorCode> </MyError>");
errXMl.Replace("ERROR_STRING", erroString);
errXMl.Replace("ERROR_CODE", errorCode);
return errXMl.ToString();
}
Now save the application and run it with the below XML. You should be seeing SUCCESS
message on the web page:
<Person xmlns:ns0="http://Testing.Message">
<Name>Surya Prakash</Name>
<Address>Malkajgiri</Address>
<Phone>9966537965</Phone>
<Email>suryaprakasash.bg@gmail.com</Email>
</Person>
So far so good, let's modify the XML as follows:
- Add an extra tag, which is not defined in XSD. So run the application and look at the exception.
Now the XML would look as:
<Person xmlns:ns0="http://Testing.Message">
<Name>Surya Prakash</Name>
<Address>Malkajgiri</Address>
<Phone>9966537965</Phone>
<Email>suryaprakasash.bg@gmail.com</Email>
<EmpId>123592</EmpId>
</Person>
- Provide invalid email in
EMAIL
tag. So run the application and look at the exception.
Now the XML would look as:
<Person xmlns:ns0="http://Testing.Message">
<Name>Surya Prakash</Name>
<Address>Malkajgiri</Address>
<Phone>9966537965</Phone>
<Email>suryaprakasash.bg@gmail.@.com.com</Email>
</Person>
Happy coding… hope this helps!