Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate an XML document against a DTD in C#?

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);
like image 376
Matthew Avatar asked Nov 01 '09 21:11

Matthew


People also ask

How a XML document is validated What is DTD?

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.

When an XML document validated against a DTD is both?

An XML document with correct syntax is called "Well Formed". An XML document validated against a DTD is both "Well Formed" and "Valid".


1 Answers

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.

like image 152
mmx Avatar answered Nov 14 '22 22:11

mmx