Todd Bright wrote:
I wanted to display the datatype that the node is declared as in the XSD file
(string, short, int,...) But I couldn't find a way to link the reader and
the XSD schema up so that I could get to that information when an error
occurs. Seems that when an error such as a value out of range occurs, by the
time the validation error routine is called it is on the end element of
whatever node the error occured in.
I have now tried to store the SchemaType property the reader exposes and
access it in the validation event handler as follows:
using System;
using System.Xml;
using System.Xml.Schema;
public class Test2005032601 {
private bool valid;
private object currentSchemaType;
public static void Main (string[] args) {
Test2005032601 test = new Test2005032601();
System.Threading.Thread.CurrentThread.CurrentCultu re = new
System.Globalization.CultureInfo("en-US");
test.Validate(args[0]);
}
public void Validate (string xmlURL) {
XmlValidatingReader xmlValidator = new XmlValidatingReader(new
XmlTextReader(xmlURL));
xmlValidator.ValidationEventHandler += new
ValidationEventHandler(ValidationHandler);
valid = true;
currentSchemaType = null;
Console.WriteLine("Starting validation of {0}:", xmlURL);
while (xmlValidator.Read()) {
if (xmlValidator.NodeType == XmlNodeType.Element ||
xmlValidator.NodeType == XmlNodeType.Attribute) {
currentSchemaType = xmlValidator.SchemaType;
}
}
xmlValidator.Close();
Console.WriteLine("Validation finished: XML document is {0}.",
valid ? "valid" : "not valid");
}
void ValidationHandler (object sender, ValidationEventArgs args) {
if (args.Severity == XmlSeverityType.Error) {
valid = false;
}
Console.WriteLine("Validation {0}: {1}.", args.Severity, args.Message);
if (currentSchemaType != null) {
if (currentSchemaType is XmlSchemaDatatype) {
XmlSchemaDatatype dataType = (XmlSchemaDatatype)currentSchemaType;
Console.WriteLine("Type should be {0}, .NET type {1}.",
dataType, dataType.ValueType);
}
}
}
}
That then gives information alike
Type should be System.Xml.Schema.Datatype_NCName, .NET type System.String.
when a type of an element or attribute is not correct. Unfortunately
classes like System.Xml.Schema.Datatype_NCName do not seem to be part of
the public classes the .NET framework exposes, there is only the
abstract class XmlSchemaDatatype that is documented.
--
Martin Honnen
http://JavaScript.FAQTs.com/