I don't want to do anything fancy, I just want to make sure a document is valid, and print an error message if it is not. Google pointed me to this, but it seems XmlValidatingReader is obsolete (at least, that's what MonoDevelop tells me).
Edit: I'm trying Mehrdad's tip, but I'm having trouble. I think I've got most of it, but I can't find OnValidationEvent anywhere. Where go I get OnValidationEvent from?
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.DTD;
settings.ValidationEventHandler += new ValidationEventHandler(/*trouble is here*/);
XmlReader validatingReader = XmlReader.Create(fileToLoad, settings);
An XML document that is well created can be validated using DTD (Document Type Definition) or XSD (XML Schema Definition). A well-formed XML document should have correct syntax and should follow the below rules: It must start with the XML declaration. It must have one unique root element enclosing all the other tags.
An XML document with correct syntax is called "Well Formed". An XML document validated against a DTD is both "Well Formed" and "Valid".
Instead of creating XmlValidatingReader
class directly, you should construct an appropriate XmlReaderSettings
object and pass it as an argument to the XmlReader.Create
method:
var settings = new XmlReaderSettings { ValidationType = ValidationType.DTD };
settings.ValidationEventHandler += new ValidationEventHandler(OnValidationEvent);
var reader = XmlReader.Create("file.xml", settings);
The rest is unchanged.
P.S. OnValidationEvent
is the name of the method you declare to handle validation events. Obviously, you can remove the line if you don't want to subscribe to validation events raised by the XmlReader
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With