
Untitled
By: a guest on
Apr 28th, 2012 | syntax:
None | size: 2.30 KB | hits: 17 | expires: Never
Why don't I get schema information when using an XPathDocument with a validating XmlReader?
using System;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Schema;
namespace XmlSchemaTest
{
class Program
{
static void Main(string[] args)
{
var xpathDocument = ReadAndValidateXmlFile(@"c:tempxmltest.xml", @"C:tempxmltest.xsd");
if (xpathDocument == null)
Console.WriteLine("Cannot open document.");
else
{
var xpathNavigator = xpathDocument.CreateNavigator();
var xpathNodeIterator = xpathNavigator.Select("/Data/FloatValue");
if (!xpathNodeIterator.MoveNext())
Console.WriteLine("No matches.");
else
{
Console.WriteLine("SchemaInfo is " + ((xpathNodeIterator.Current.SchemaInfo == null) ? "null" : "not null"));
Console.WriteLine("XmlType is " + ((xpathNodeIterator.Current.XmlType == null) ? "null" : "not null"));
Console.WriteLine("TypedValue is " + xpathNodeIterator.Current.TypedValue.GetType().ToString());
}
}
Console.ReadLine();
}
private static XPathDocument ReadAndValidateXmlFile(string xmlPath, string xsdPath)
{
var xmlReaderSettings = new XmlReaderSettings();
xmlReaderSettings.ValidationType = ValidationType.Schema;
xmlReaderSettings.Schemas.Add(targetNamespace: null, schemaUri: xsdPath); // null means use the target namespace referenced by the XML document
bool anyValidationErrors = false;
xmlReaderSettings.ValidationEventHandler += new ValidationEventHandler((object sender, ValidationEventArgs args) => anyValidationErrors = true );
using (var xmlReader = XmlReader.Create(xmlPath, xmlReaderSettings))
{
// Note: a document will be created even if there are validation errors,
// but for our purposes we'll discard 'invalid' documents.
var xpathDocument = new XPathDocument(xmlReader);
if (anyValidationErrors)
return null;
else
return xpathDocument;
}
}
}
}