Prizes & Awards
My Profile
Active Members
TodayLast 7 Days
more...
|
New Feature: Community Sites:
Create your own .NET community website and start earning from Google AdSense !
It's Free !
|
XML Validation using XSD in .Net 2.0
Posted Date: 03 Jan 2008 Resource Type: Articles Category: .NET Framework
|
Posted By: vijeta Member Level: Bronze Rating: Points: 10
|
In this article, we will look at the following things: 1. Creating a sample XML file. 2. Creating the corresponding XSD schema file. 3. Reading the XML file data and path where XSD file is located. 4. Using the above gathered data, validating the XML against the XSD using .net classes like XMLReaderSettings. The classes used for validation will be explained as we move further.
Creating a sample XML and the corresponding XSD schema file The sample xml file which needs to be validated looks something like this:
<Envelope> <Header> <Context> <messageId>11111</messageId> <creationTimestamp></creationTimestamp> </Context> <Path> <to>FP</to> <action>sendToProcessor</action> <behaviorVersion>1.0</behaviorVersion> </Path> </Header> <Body> <Request> <ID>1</ID> </Request> </Body> </Envelope>
Using VS2005, add a new website and then add a new XML file to it, say Request.xml. Copy the above content to the xml file.
Now to create the XSD schema, click on XML which appears on the top-most menu of VS2005 and select ‘Create Schema’. A schema file is automatically generated for your XML file. Save the schema to the any location of your choice (as a good practice, create a XSD folder under your website and save schema to that folder). The schema generated is as follows:
<?xml version="1.0" encoding="utf-8"?> <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="Envelope"> <xs:complexType> <xs:sequence> <xs:element name="Header"> <xs:complexType> <xs:sequence> <xs:element name="Context"> <xs:complexType> <xs:sequence> <xs:element name="messageId" type="xs:unsignedShort" />
Reading the XML file data and path where XSD file is located Just few lines of code to read the XML data and XSD file path.
string requestXMLPath = HttpRuntime.AppDomainAppPath + "Request.xml"; string XSDFilePath = HttpRuntime.AppDomainAppPath + "XSD/Request.xsd"; StreamReader streamreader = new StreamReader(requestXMLPath); string XMLData = streamreader.ReadToEnd();
Validating the XML against the XSD Now we create a method which takes XMLData and XSD file path as input parameters and write validation code in that method. The method returns • true if validation is successful • false if validation fails
The code contained in the method is as follows:
Stream s = new MemoryStream(ASCIIEncoding.Default.GetBytes(XMLData)); XmlReader reader = null; XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationEventHandler += new ValidationEventHandler(this.ValidationEventHandler); settings.ValidationType = ValidationType.Schema; settings.Schemas.Add(null, XmlReader.Create(XSDFilePath)); reader = XmlReader.Create(s, settings); while (reader.Read()) {
} if (_builder.ToString() == string.Empty) { //validation successsful } else { //validation failed }
Following sequence of steps are followed in the code above to perform validation:
1. Using the XmlReaderSettings class object, assign the a. Validation event handler b. Validation type - Set it to Schema as we are performing schema validation. c. Add the schema to collection of schemas using Add method of Schema class. 2. The XmlReader’s Create method is used to read the XML data by passing the xmldata and the XMLReaderSettings object as argument. If any errors are encountered during read, the validation event handler handles those errors and appends them to _builder string. 3. If _builder string is empty, it signifies that XML validation is successful otherwise XML validation failed.
Validation Event Handler The validation event handler is defined as follows:
void ValidationEventHandler(Object sender, ValidationEventArgs args) { _builder.Append(" Validation Error:" + args.Message); }
args.Message specifies the error message generated during XML parsing. The validation event handler appends this error message to a StringBuilder object _builder.
Summary Follow this simple sequence of steps and we are done with XML Validation.
.Net offers various ways of playing with XML data. This article explains some simple ways to read XML data, generate XSD and validate the XML data.
Until next time, Happy Coding!
|
Responses
|
No responses found. Be the first to respond and make money from revenue sharing program.
|
|