As you may be aware, the XMLValidatingReader has been depricated in version 2.0 of the .Net framework, so how do you validate XML now? Well, given the following XML
<?xml version="1.0" encoding="utf-8" ?>
<books>
<book>
<author>
<firstName>Gary</firstName>
<surname>Short</surname>
</author>
<title>My Book</title>
</book>
</books>
and the following XSD schema
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema id="Books"
elementFormDefault="qualified"
xmlns="http://tempuri.org/Books.xsd"
xmlns:mstns="http://tempuri.org/Books.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="books">
<xs:complexType>
<xs:sequence>
<xs:element
name="book"
minOccurs="1"
maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element
name="author"
minOccurs="1"
maxOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element
name="fistName"
minOccurs="1"
maxOccurs="1" />
<xs:element
name="surname"
minOccurs="1"
maxOccurs="1" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element
name="title"
type="xs:string"
minOccurs="1"
maxOccurs="1" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
you can validate the XML against the schema like so
/// <summary>
/// Read and validate xml from a file path
/// </summary>
/// <param name="path2XMLFile">Path to the xml</param>
/// <param name="path2XSDFile">
/// Path to the schema file defining the xml
/// </param>
public void ReadAndValidateFromFilePath(string path2XMLFile,
string path2XSDFile)
{
using (FileStream fs =
File.Open(path2XMLFile, FileMode.Open, FileAccess.Read))
{
//GS - Create an xml document to hold our xml
XmlDocument xdoc = new XmlDocument();
//GS - Create a reader settings, add the schema, set for
//schema validation and add a validation event handler
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, path2XSDFile);
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler +=
new ValidationEventHandler(settings_ValidationEventHandler);
//GS - Load and validate the xml
XmlReader reader = XmlReader.Create(fs, settings);
xdoc.Load(reader);
//GS - Close the file stream when we're done
fs.Close();
_XML = xdoc.OuterXml;
}
}
/// <summary>
/// GS - Handle any validation events raised
/// </summary>
/// <param name="sender">Object</param>
/// <param name="e">ValidationEventArgs</param>
void settings_ValidationEventHandler(object sender, ValidationEventArgs e)
{
_SchemaValidationErrors += e.Message;
}