Click here to Skip to main content
6,595,854 members and growing! (17,428 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate License: The Code Project Open License (CPOL)

XML Validation Patterns in .NET 2.0 using C#

By Edward Moemeka

This article highlights some ways to validate inbound XML documents .NET 2.0 using the C# programming language. It also addresses some changes to the general pattern from .NET 1.1
C#, Windows, .NET, Visual Studio, Dev
Posted:28 Feb 2006
Views:52,046
Bookmarked:17 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
11 votes for this article.
Popularity: 2.65 Rating: 2.54 out of 5
2 votes, 20.0%
1
2 votes, 20.0%
2
1 vote, 10.0%
3
3 votes, 30.0%
4
2 votes, 20.0%
5

Introduction

If anyone does not know this, here is a quick code snippet that shows one way to validate an XML document.

FileStream fs = File.Open("../../signatureinstance.xml", FileMode.Open);
XmlTextReader reader = new XmlTextReader(fs);
XmlValidatingReader xvr = new XmlValidatingReader(reader);
xvr.ValidationType = ValidationType.Schema;
xvr.Schemas.Add(null, "../../signatureschema.xsd");
xvr.ValidationEventHandler += new ValidationEventHandler(xvr_ValidationEventHandler);
XmlDocument xdoc = new XmlDocument();
xdoc.Load(xvr);

In the above example, the XML instance to be validated is signatureinstance.xml.  The schema doing the validation is signature.xsd.  A type called XmlValidatingReader, found in the System.Xml namespace, is used to perform the validation at load time.  (It is also possible to load the XmlDocument first and use the Validate() function to validate the contents against a given schema.

Just in case anyone reading does not understand how I might have gotten to this point, I will go through a few steps (using the Visual Studio .NET 2005 IDE).

The first step (after creating a project of course) is adding a schema to your project.  The XML schema template should be listed amongst other document types that can be added. Make sure not to select Dataset; although they both use .xsd extensions and are essentially the same technology, there are some differences. The item we are looking for is shown in the picture below:

addschematoproject.jpg

Next we design the schema using the toolbox, which at this point should have changed to a list of tools related to editing XML schemas. The new toolbox view is illustrated in the picture below:

schematoolbox.jpg

Now we can design our schema. The Signature schema design is given below:

schema.jpg

Once that's done, we can work on creating a sample instance using the schema as a reference. VS.NET 2005 allows you to associate a given schema to the instance you are currently working with. The schema property can be found on the property pane. 

associateschema.jpg

When you click on the ellipsis for the schema property, a property page with all the currently known schemas will appear:

schemaselector.jpg

You can use this tool to add more known schemas. For this project, select the signature schema designed.

Using this, I created the schema shown below:

<?xml version="1.0" encoding="utf-8" ?>
<Signature xmlns="http://tempuri.org/XMLSchema1.xsd">
<Company>
Perficient Inc.
</Company>
<Name>Jerod Edward Moemeka</Name>
<Position>Architect</Position>
<OfficeAddress>
<Address>622 Emerson Road</Address>
<Suite>400</Suite>
<City>St. Louis</City>
<State>MO</State>
<Zip>63141</Zip>
</OfficeAddress>
<ContactInfo>
<EmailAddress>jerod.moemeka@perficient.com</EmailAddress>
<CompanyURL>www.perficient.com</CompanyURL>
<PhoneInfo>
<OfficePhoneNumber>1234567890</OfficePhoneNumber>
<MobileNumber>9876543210</MobileNumber>
<FaxNumber>1112223333</FaxNumber>
</PhoneInfo>
</ContactInfo>
</Signature>

At this point, validation using the example above will work.  However, there are also some other ways to accomplish this. If for instance, you did not mind the document being loaded ahead of time and then validated, you could use the DOM object directly to validate as follows:

XmlDocument xdoc = new XmlDocument();
xdoc.Load("../../signatureschemainstance.xml");
xdoc.Schemas.Add(null, "../../signatureschemaschema.xsd");
ValidationEventHandler veh = new ValidationEventHandler(xvr_ValidationEventHandler);
xdoc.Validate(veh);

In .NET 2.0, the XmlValidatingReader is deprecated, hence the initial example should be as follows:

//load instance into memory
FileStream fs = File.Open("../../signatureinstance.xml", FileMode.Open);
XmlDocument xdoc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, "../../signatureschema.xsd");

//add resolver to pass security if accessing web site to receive schema
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;
settings.XmlResolver = resolver;

//this line is necessary for validation to work
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler +=
	new ValidationEventHandler(xvr_ValidationEventHandler);
XmlReader reader = XmlReader.Create(fs, settings);
xdoc.Load(reader);
fs.Close();

To load the schema once and not continually, go get it from the source URL (in this case ../../signatureschema.xsd. We can rewrite this to use the Schema object as follows:

ValidationEventHandler veh = new ValidationEventHandler(xvr_ValidationEventHandler);
XmlSchema schema = XmlSchema.Read(new XmlTextReader("../../productschema.xsd"), veh);

FileStream fs = File.Open("../../productcataloginstance.xml", FileMode.Open);
XmlDocument xdoc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(schema);
//this line is necessary for validation to work
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler +=
	new ValidationEventHandler(xvr_ValidationEventHandler);
XmlReader reader = XmlReader.Create("../../productcataloginstance.xml", settings);
xdoc.Load(reader);

History

  • 28th February, 2006: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Edward Moemeka


Member
Hi I'm Edward Moemeka,
For more interesting articles about stuff check out my blog at http://moemeka.blogspot.com
To correspond, email me at edward.moemeka@synertry.com
To support my company, thus help me feed my family, check out our awesome online preview at www.synertry.com. Remember, its in alpha Wink
Location: United States United States

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 11 of 11 (Total in Forum: 11) (Refresh)FirstPrevNext
GeneralI am unable to make link between XSD and XML Pinmemberchirag_pandey3:27 13 Jun '09  
GeneralRe: I am unable to make link between XSD and XML PinmemberEdward Moemeka17:43 17 Jun '09  
QuestionXML Validation problem PinmemberGorets5:08 3 Jan '08  
GeneralRe: XML Validation problem PinmemberGorets5:13 3 Jan '08  
GeneralXmlValidatingReader is obsolete Pinmembernvt1:07 22 Jun '07  
GeneralRe: XmlValidatingReader is obsolete PinmemberAndyCLon5:30 21 May '08  
GeneralWhy not simplier? PinmemberArjunachan1:31 30 May '06  
GeneralRe: Why not simplier? Pinmemberabnorm22:32 25 Jul '06  
GeneralHere's a more efficient way to do this.... PinmemberDaveBlack11:14 2 Apr '07  
GeneralRe: Here's a more efficient way to do this.... Pinmemberc00ks5:04 17 Oct '07  
GeneralRe: Why not simplier? Pinmembervalamas16:37 21 Oct '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 28 Feb 2006
Editor: Deeksha Shenoy
Copyright 2006 by Edward Moemeka
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project