XML Document validation against XSD schema

G

Guest

Hi,

I got this code to validate my XML against a XSD schema, and it works fine.

static void ValidatingProblemHandler(object sender, ValidationEventArgs e)
{
if ((e.Severity == XmlSeverityType.Warning) || (e.Severity ==
XmlSeverityType.Error))
{
MessageBox.Show(e.Message + " " + String.Format("\n\nLine: {0},
Position: {1} \"{2}\"",
e.Exception.LineNumber, e.Exception.LinePosition,
e.Exception.Message));
}
}


XmlDocument xDoc = new XmlDocument();
xDoc.Load(@"c:\Request.xml");
xDoc.Schemas.Add("",@"c:\ApplicationCompletionRequest.xsd");
xDoc.Schemas.Compile();
ValidationEventHandler validator = ValidatingProblemHandler;
xDoc.Validate(validator);


I would like to know which node of the document the validation failed, not
only the node name and the value, which could be duplicated in more than one
part in my XML document due to the structure of my XML document


Any suggestion?


Thanks,
Filippo
 
M

Martin Honnen

Filippo said:
XmlDocument xDoc = new XmlDocument();
xDoc.Load(@"c:\Request.xml");
xDoc.Schemas.Add("",@"c:\ApplicationCompletionRequest.xsd");
xDoc.Schemas.Compile();
ValidationEventHandler validator = ValidatingProblemHandler;
xDoc.Validate(validator);


I would like to know which node of the document the validation failed, not
only the node name and the value, which could be duplicated in more than one
part in my XML document due to the structure of my XML document

Each node has a property SchemaInfo which you can access after
validation, it has a property Validity:
<http://msdn2.microsoft.com/en-us/library/system.xml.xmlnode.schemainfo.aspx>
<http://msdn2.microsoft.com/en-us/library/system.xml.schema.ixmlschemainfo.validity.aspx>
 
M

Martin Honnen

Filippo said:
I got this code to validate my XML against a XSD schema, and it works fine.

static void ValidatingProblemHandler(object sender, ValidationEventArgs e)
{
if ((e.Severity == XmlSeverityType.Warning) || (e.Severity ==
XmlSeverityType.Error))
{
MessageBox.Show(e.Message + " " + String.Format("\n\nLine: {0},
Position: {1} \"{2}\"",
e.Exception.LineNumber, e.Exception.LinePosition,
e.Exception.Message));
}
}


XmlDocument xDoc = new XmlDocument();
xDoc.Load(@"c:\Request.xml");
xDoc.Schemas.Add("",@"c:\ApplicationCompletionRequest.xsd");
xDoc.Schemas.Compile();
ValidationEventHandler validator = ValidatingProblemHandler;
xDoc.Validate(validator);


I would like to know which node of the document the validation failed,

In your validation event handler you can cast
XmlSchemaValidationException ex = e.Exception as
XmlSchemaValidationException;
then
XmlNode node = ex.SourceObject as XmlNode;
that way you get the node in the XML object the exception relates to.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top