views:

313

answers:

2

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);
+4  A: 

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.

Mehrdad Afshari
Where do you get OnValidationEvent from? See my edit.
Matthew
Matthew: That's the method you'd declare to handle failed validation events. You can remove that line altogether if you want it to throw exception instead.
Mehrdad Afshari
A: 
var messages = new StringBuilder();
var settings = new XmlReaderSettings { ValidationType = ValidationType.DTD };
settings.ValidationEventHandler += (sender, args) => messages.AppendLine(args.Message);
var reader = XmlReader.Create("file.xml", settings);

if (messages.Length > 0)
{
    // Log Validation Errors
    // Throw Exception
    // Etc.
}

ValidationEventHandler

Lambda Expressions

Type Inference

ChaosPandion
Um, didn't Mehrdad give essentially the same answer, 22 minutes before you did?
Robert Harvey
This answer is a different way of accomplishing the same thing.
ChaosPandion