Validating XML Files Against XSD Schemas in .NET 1.x and 2.0
page 3 of 6
by Keyvan Nayyeri
Feedback
Average Rating: 
Views (Total / Last 10 Days): 77378/ 33

.NET 2.0

Things are a bit different for some steps in .NET 2.0 because there are obsolete objects we used for validation in .NET 1.x.

1.      Read the XML file content as Stream, TextReader or XmlReader.

2.      Read the Schema file content as Stream, TextReader or XmlReader.

3.      Create a new instance of XmlSchema object.

4.      Set XmlSchema object by calling XmlSchema.Read() method and passing the content of Schema file and ValidationEventHandler method address to it.

5.      Create a new instance of XmlReaderSettings object.

6.      Set ValidationType for XmlReaderSettings object to Schema.

7.      Add your XmlSchema object to XmlReaderSettings Schemas collection by calling its Schemas.Add() method.

8.      Add your ValidationEventHandler method address to XmlValidationReader's ValidationEventHandler handler.

9.      Create a new instance of XmlReader object and pass your XML file content (as Stream or a Reader object) and XmlReaderSettings object to it.

10.  Call Read() method of the Reader or Stream object to contain your XML file content in a loop to parse and validate it completely.

11.   Add your logic to ValidationEventHandler method you created to implement what you want to be done in the validation process.

Here I have upgraded the previous code for .NET 2.0:

Listing 2

private void ValidatingProcess(string XSDPath, string XMLPath)
{
    try
    {
        // 1- Read XML file content
        this.Reader = new XmlTextReader(XMLPath);
 
        // 2- Read Schema file content
        StreamReader SR = new StreamReader(XSDPath); 
 
        // 3- Create a new instance of XmlSchema object
        XmlSchema Schema = new XmlSchema();
        // 4- Set Schema object by calling XmlSchema.Read() method
        Schema = XmlSchema.Read(SR, 
            new ValidationEventHandler(ReaderSettings_ValidationEventHandler)); 
 
        // 5- Create a new instance of XmlReaderSettings object
        XmlReaderSettings ReaderSettings = new XmlReaderSettings();    
        // 6- Set ValidationType for XmlReaderSettings object
        ReaderSettings.ValidationType = ValidationType.Schema;                
        // 7- Add Schema to XmlReaderSettings Schemas collection
        ReaderSettings.Schemas.Add(Schema); 
 
        // 8- Add your ValidationEventHandler address to
        // XmlReaderSettings ValidationEventHandler
        ReaderSettings.ValidationEventHandler += 
            new ValidationEventHandler(ReaderSettings_ValidationEventHandler);
 
        // 9- Create a new instance of XmlReader object
        XmlReader objXmlReader = XmlReader.Create(Reader, ReaderSettings);
 
 
        // 10- Read XML content in a loop
        while (objXmlReader.Read())
        { /*Empty loop*/} 
 
    }//try
    // Handle exceptions if you want
    catch (UnauthorizedAccessException AccessEx)
    {
        throw AccessEx;
    }//catch
    catch (Exception Ex)
    {
        throw Ex;
    }//catch
}
 
private void ReaderSettings_ValidationEventHandler(object sender, 
    ValidationEventArgs args)
{
    // 11- Implement your logic for each validation iteration
    string strTemp;
    strTemp = "Line: " + this.Reader.LineNumber + " - Position: " 
        + this.Reader.LinePosition + " - " + args.Message; 
 
    this.Results.Add(strTemp);
}

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-2024 ASPAlliance.com  |  Page Processed at 2024-04-19 5:30:00 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search