XmlValidatingReader is obsolete!

The way you read XML files with validation has been changed in .Net 2.0. Before we could do this:

StringReader sr = new StringReader(xmlfragment);
XmlTextReader tr = new XmlTextReader(sr);

XmlValidatingReader vr = new XmlValidatingReader(tr);
vr.Schemas.Add("", Path.Combine( _sInstallDir, @"Schemas\schema.xsd"));
vr.ValidationType = ValidationType.Schema;
vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);

while (vr.Read())
{
   ...
}

That still works (in Beta 2 of VS2k5) but will give “obsolete” warnings. Apparently this is the way to go now:

StringReader sr = new StringReader(xmlfragment);

XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, Path.Combine(_sInstallDir, @"Schemas\schema.xsd"));
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);

XmlReader reader = XmlReader.Create(sr, settings);


while (reader.Read())
{
   ...
}

It’s very similar so I’m not quite sure as to why the modification has been made. Maybe to limit the number of classes in the System.Xml namespace?

Note that you can also use this method with XmlWriter. I haven’t tried that yet, though.

1 thought on “XmlValidatingReader is obsolete!”

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.