how to use xsd proof xml-string from xmldocument

  • Thread starter Thread starter David
  • Start date Start date
D

David

I have a xmldocument like this:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml-string);

and I have a .xsd file, "schema.xsd".

How do I use this xsd file to valid the string?
Otherwise how do I trans the doc to XmlTextReader and valid it?
Thanks for any advice, David.
 
David said:
How do I use this xsd file to valid the string?

using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
// . . .

private bool isSchemaValid;

// . . .
private void btnValidate_Click( object sender, EventArgs args)
{
// . . .
this.isSchemaValid = true;
string targetNamespaceURI = "urn:your-schema-com"; // put the target namespace URI of your schema here.
XmlValidatingReader reader = new XmlValidatingReader( new XmlTextReader( new StringReader( xml_string ) ) );
reader.Schemas.Add( targetNamespaceURI, "schema.xsd");
reader.ValidationEventHandler += new ValidationEventHandler( xmlDocument1_ValidationCallBack);

XmlDocument xmlDocument1 = new XmlDocument( );
xmlDocument1.Load( reader); // this will call Read( ) on the XmlValidatingReader, which schema-validates as it loads.
// . . .
// . . . any schema errors will result in the callback method being called while Load( ) processes.
// . . .
Console.WriteLine( "\r\n\tSchemaValid = " + this.isSchemaValid.ToString( ) );
// . . .
}
// . . .
private void xmlDocument1_ValidationCallBack( object sender, ValidationEventArgs args)
{
isSchemaValid = false;
Console.WriteLine( "\r\n\tValidation Error: " + args.Message );
}


Derek Harmon
 
Thank you, Derek.

If I wrote it in .dll and deploy it to another server,
how should I assign the xsd file path in reader.Schemas.Add(
targetNamespaceURI, "schema.xsd")?

Thanks, David.
 
Back
Top