New Leaf Technology Home - Freelance Web Developer & IT Consultant located in Twyford, Reading, Berkshire

How to read and validate XML using XmlReader and XSD in ASP.NET

If the XML document does not specify a namespace then validate it as a XML fragment using the XmlParserContext to set the default namespace. This example uses a XmlReader.

Hope this helps! Comments.

Back to developer tips

public int Validation(string xml)
{
// XML Validation using XSD

XmlSchemaSet sc = new XmlSchemaSet();
sc.Add(null, "http://www.newleaftech.net/XMLSchema.xsd");
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = sc;
settings.ValidationEventHandler += new ValidationEventHandler(ReaderSettings_ValidationEventHandler);
// Create an XmlNamespaceManager to resolve namespaces.
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
nsmgr.AddNamespace(String.Empty, "urn:newleaftech");

// Create an XmlParserContext. The XmlParserContext contains all the information
// required to parse the XML fragment, including the entity information and the
// XmlNamespaceManager to use for namespace resolution.
XmlParserContext context = new XmlParserContext(nt, nsmgr, null, XmlSpace.Default);

TextReader tr = new StringReader(xml);

XmlReader reader = XmlReader.Create(tr, settings, context);

validationException = 0;

while (reader.Read()) { };

return validationException;
}
private void ReaderSettings_ValidationEventHandler(object sender, ValidationEventArgs args)
{
validationException = -1;
}