SgDotNet
Singapore Professional .NET User Group -For Cool Developers

how to validate an XML file is correct according to a given XSD file?

rated by 0 users
This post has 2 Replies | 0 Followers

Top 75 Contributor
Posts 38
HoeKeat Posted: 06-12-2005 10:58 PM

have been trying things out and found an interesting article at

http://support.microsoft.com/kb/307379/EN-US/

but somehow, the code given prompted me more errors than i can understand, making the whole thing useless. Any other better recomendation?

One thing from the article made me think for a while. Is it a must that the link to an xsd file have to be stored inside the xml file?

Top 10 Contributor
Posts 762

Validate xml with schemas... try this :)

string strPath = Application.StartupPath + @"\Sample.xml";

XmlSchema schema = XmlSchema.Read(new XmlTextReader(Application.StartupPath + @"\Sample.xsd"), null);

// define handler for compile errors

ValidationEventHandler handler = new ValidationEventHandler(this.CompileErrors);

XmlTextReader reader;

XmlValidatingReader valid;

try

{

reader = new XmlTextReader(strPath);

valid = new XmlValidatingReader(reader);

valid.Schemas.Add(schema);

valid.ValidationType = ValidationType.Schema;

while (valid.Read())

{

// endless loop to read

}

lstResult.Items.Add("XML Script contains no errors");

}

catch (Exception ex)

{

lstResult.Items.Add("XML Error " + ex.Message);

}

finally

{

reader = null;

valid = null;

schema = null;

}

-----------

I believe it is not ncessary. I have tested it here. The only reason why the xsd link is in the xml file is because when you create a schema from a xml in VS.NET, it will auto include the link in that xml.

Hope it helps you somehow :)

Regards, Chua Wen Ching Believe in yourself, and you will succeed
Top 25 Contributor
Posts 442
 HoeKeat wrote:

One thing from the article made me think for a while. Is it a must that the link to an xsd file have to be stored inside the xml file?

If you have link the XSD file from the XML file appropriately, then when you validate using XmlValidatingReader, you don't have to add the schema anymore.

The following line is unnecessary if you have the link.

valid.Schemas.Add(schema);

Maung Maung

Maung Maung
Page 1 of 1 (3 items) | RSS
Copyright SgDotNet 2004-2008
Powered by Community Server (Commercial Edition), by Telligent Systems