XML Document validation against XSD schema

  • Thread starter Thread starter Guest
  • Start date Start date
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
 
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>
 
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.
 
Back
Top