Validating XML Files Against XSD Schemas in .NET 1.x and 2.0
page 1 of 6
Published: 14 Aug 2006
Unedited - Community Contributed
Abstract
Validating XML files is a common task in software development for developers. There are three ways to validate XML files: XSD Schema, DTD and Relax NG. In .NET XSD Schema is the preferred way to validate XML files. In this article I will dicuss both approaches and will give code samples to implement them both.
by Keyvan Nayyeri
Feedback
Average Rating: 
Views (Total / Last 10 Days): 157818/ 185

Introduction

XSD Schema, DTD and Relax NG are three common ways to validate a XML file structure.  The first approach, XSD Schema, has been supported by Microsoft .NET Framework and is the best approach for .NET developers.  Schema files are a special kind of XML file that define the structure of an XML file via some pre-defined elements and attributes.

Using this Schema file you can validate your XML file to make sure it fits to your application's needs to prevent any exception in your code.  There are several free or commercial tools which do this validation for you, but in many cases you need to accomplish this task in your own applications with your code.

Fortunately, .NET has provided all the tools to do this and all you need is to apply these tools.  The process to do this is a bit different in .NET 2.0 because a main object for this process in .NET 1.x is obsolete in .NET 2.0.

Here I give you the steps you need to do this in both .NET 1.x and 2.0.


View Entire Article

User Comments

Title: Test   
Name: Panaym
Date: 2012-08-10 3:44:45 AM
Comment:
Test
Title: Thanks Shahid Iqbal   
Name: kalrashi
Date: 2011-08-23 9:34:52 PM
Comment:
Thanks Keyvan for the handy code, saved me at least 30 minutes from figuring it out by digging MSDN.

Another kudos to Shahid Iqbal for pointing out the miossing piece.
Title: Project Manager @ CureMD Corporation   
Name: Shahid Iqbal
Date: 2010-03-02 9:25:38 AM
Comment:
GOOD JOB!! but the missing step is to set validation flags as "ReportValidationWarnings" which is required to validate entire xml structure...

ReaderSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;

because this flag is not enabled (by default) and validator ignores structural errors as considering them warnings even the root element doesnt match the schema

Thnx
Shahid
Title: Pretty idiotic AndyF   
Name: RubenH
Date: 2010-01-23 9:42:49 PM
Comment:
As you can see AndyF... at least since march 2007 everybody knows that need an schema to validate a XML... or you think the program can choise the rigth one by itself?

Are you sure you know what are you doing? If you dont have an XSD be gratefull because this article teach you taht you need one... Moron

And your comment about the moon and the spaceshuttle its so...


Great work Keyvan
Title: Pretty idiotic   
Name: AndyF
Date: 2010-01-21 2:06:46 PM
Comment:
Oh, so great - all I need to validate XML is an XSD file. Wonderful! And WHAT the heck do I do if I DONT have an XSD file? Do you get the point?

Its easy to fly to the Moon for lunch - all you need is your own spaceshuttle, and a few mega-gallons of liquid nitrogen. Told ya, Easy huh?

Next time youre going to offer an "easy" way to do something, you might think about NOT presuming every XML file ever created my mankind has an XSD file. Moron!
Title: VERY GOOD   
Name: MARCO A
Date: 2009-12-04 6:57:54 AM
Comment:
YOU'RE GREAT !!!!!!
Title: Nice article   
Name: Vijay Jadhav
Date: 2009-05-06 10:14:15 AM
Comment:
Thanks for your code. This works in Gr8 manner. Thanks for a such article.
Title: Just right   
Name: Andy
Date: 2009-05-01 1:51:45 PM
Comment:
Thankyou, this is clearer than the Microsoft documentation on XML validation. You've saved me a lot of time!
Title: Good idea   
Name: Kristoffer Sjöwall
Date: 2009-01-30 5:23:24 AM
Comment:
It's probably a good idea to close the StreamReader object (SR) aswell as the XmlTextReader object (Reader) at end.
Title: please help me   
Name: T V N
Date: 2008-12-13 3:17:03 AM
Comment:
public static string valid1(XmlDocument xmlDoc, XmlTextReader xsdDoc)
{
validationMessage = string.Empty;
XmlSchemaCollection xsc = new XmlSchemaCollection();
xsc.Add(string.Empty, xsdDoc);
XmlTextReader reader = new XmlTextReader(new MemoryStream(ASCIIEncoding.ASCII.GetBytes(xmlDoc.OuterXml)));
XmlValidatingReader validator = new XmlValidatingReader(reader);
validator.Schemas.Add(xsc);
validator.ValidationEventHandler += new ValidationEventHandler(Functionerr);
while (validator.Read()) {}
validator.Close();
return validationMessage;
}
public static void Functionerr(object sender, ValidationEventArgs args)
{
validationMessage = args.Message;
}
Some PC run ok, but some PC not run and validationMessage return 1.
can I help me.
thanks a lot
Title: xml   
Name: Raghu
Date: 2008-11-14 8:59:05 AM
Comment:
need to validate xml with xsd
Title: Senior Software Consultant   
Name: Jeff Huckins
Date: 2008-08-22 11:04:44 AM
Comment:
Just like somebody else that I see posted a message on this article, I have implemented the .NET 2.0 solution and it doesn't find any errors when I inject them. Can somebody tell me what is wrong here? (jhuckins@zaio.com)

Thanks in advance
Jeff
Title: Thanks Sandeep Meravi, Meghna Godhani   
Name: dev
Date: 2008-07-07 8:21:56 AM
Comment:
your code has helped me a lot, thanks a lot for this code
:)
Title: AVP   
Name: Prem
Date: 2008-06-07 8:59:19 AM
Comment:
Excellent article.
Title: Validate xml with xsd   
Name: Virus
Date: 2008-06-03 12:07:38 PM
Comment:
Its too good and working fine.
Title: Validating XML Files Against XSD Schemas in .NET 2.0   
Name: Sandeep Meravi, Meghna Godhani
Date: 2008-02-20 2:23:23 AM
Comment:
Here we are posting the most precise code to validate to an XML File using schema .

private void ValidatingXML()
{
try
{
string xmlFile = Server.MapPath("Dvdlist.xml");
string xsdFile = Server.MapPath("DVDList.xsd");


XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;

settings.Schemas.Add("", xsdFile);


XmlReader objXmlReader = XmlReader.Create(xmlFile, settings);

while (objXmlReader.Read())
{ }
}
catch (XmlSchemaValidationException e)
{
Response.Write(e.Message.ToString());
}


}
Title: How is this called?   
Name: Kevin
Date: 2008-02-14 10:41:32 PM
Comment:
Somewhat new, but I placed the *.cs file in, do a using and calling it the way I think it should be called but I keep getting the following error:

Value cannot be null.
Parameter name: schema

Can someone help me out? I'm sure I'm doing something blatantly wrong here.
Title: Developer   
Name: Lakshmi
Date: 2008-02-07 5:32:02 AM
Comment:
very nice example and presented in a good way,explaining each and every step
Thank u
Title: how to validate xmlstring or xmlnode in string format   
Name: Anki
Date: 2007-12-05 4:51:16 AM
Comment:
can anybody tell me how to validate a single xmlnode against xmlschema or nodes in string format? this example only validates a xmlfile.
Title: Validating XML Files Against XSD Schemas in .NET 1.x and 2.0   
Name: john
Date: 2007-08-21 8:11:45 PM
Comment:
I tested the code for .net 2.0, and it did not catch any of the errors i tried including:
1. node names not in the schema
2. node values that were not in an enumerated list in the schema. What does it catch?
Title: Details: Problem with XmlSchema.Read.....please help   
Name: Hemendra Vyas
Date: 2007-08-17 7:41:29 AM
Comment:
I thnk some problem came in the last post so pasting it again:

This is a part of code that inserts a sub-node inside a node.If i try for the first time after rebuilding the code this error is received. If i try again, I won't receive this message.


The Inner message is :
Could not find file"StructureLinkage.xsd"

Details
Message:
Failure to ad schema to enable nodal linkage validation-check xsd location.
Could not find file"StructureLinkage.xsd"

If after clicking on "OK" to the current message I again try it, then in the below code then the value of "schema_collection_object" in not null and is of type XMLSchemaCollection.

Please help.
Title: Problem with XmlSchema.Read.....please help   
Name: Hemendra Vyas
Date: 2007-08-17 3:29:10 AM
Comment:
Please help out in following code snippet, please reply me at hvyas@irevna.com:

For the first time it gives prompt while XmlSchema.Read(). Second time schema_collection_object is not null and so does not enter into this block of code.

Please help............



private static XmlSchemaCollection schema_collection_object;
private static XmlSchema m_ifschema;
-------
-------
-------

if (schema_collection_object==null)
{
schema_collection_object=new XmlSchemaCollection();

XmlTextReader xmlFile=new XmlTextReader(path);
//path contains the path of the .xsd file

m_ifschema=XmlSchema.Read(xmlFile,new ValidationEventHandler(ValidationCallBack));

//*******error is genarated in the above statement



m_ifSchema.Compile(newValidationEventHandler(Valid ationCallBack));

schema_collection_object.Add(m_ifSchema);
}
Title: XMl Validation   
Name: Anil Dudhani
Date: 2007-08-17 1:54:52 AM
Comment:
In some cases this validation is failed..see example send me message...
Title: Excellent Working Example   
Name: Rob
Date: 2007-06-14 10:12:18 AM
Comment:
This is the first example I've seen that both works and has a simple interface. Thanks for taking the time to write an excellent article and including a simple class that can be used very easily in other projects.
Title: Developer   
Name: sudhakar
Date: 2007-06-07 9:17:36 AM
Comment:
I am working with .Net 2.0. i am providing with the required xml string and xml schema string on which the xml string is to be validated. My code is as follows:


while (objXmlReader.Read())
{}
DataSet objDataSet=new DataSet();
objDataSet.ReadXml(Reader, XmlReadMode.Auto);


I find the data is not loaded into the dataset.. An empty dataset is returned without any exception.It was an urgent issue for me. Please help me in this regards. Thanks in advance
Title: { programmer }   
Name: selva
Date: 2007-05-17 9:00:19 AM
Comment:
Nice coding
Title: Developer   
Name: John (London)
Date: 2007-04-15 11:38:59 AM
Comment:
Many thanks for taking the time to share this - much appreciated
Title: Developer   
Name: Ramesh
Date: 2007-04-12 1:46:39 AM
Comment:
Hi,
Thanks
Title: Developer   
Name: Craig
Date: 2007-04-03 6:37:24 AM
Comment:
Thank you for taking the time to write this article.
Is there a method for performing the schema validation without referencing the schema (xsd) file separately?
My XML files all contain lines similar to this:
xsi:noNamespaceSchemaLocation="LocalSchema.xsd"
for local schema's or http references for remote schema's.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2017 ASPAlliance.com  |  Page Processed at 2017-10-19 9:31:03 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search