Validating XML
Posted 2009-11-22 13:47:39 by thomas
Here is a simple example of how you can validate xml input.
Definition of CallBack method.
XML input.
Schema definition.
// The input could come from a web service
string xml = {XML input string}
// Path to schema
string xsdFilePath = "Item.xsd";
// Set xsd schema
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(null, xsdFilePath);
// Callback handler to handle validation events
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationCallBack);
// Load xmldocument
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xml);
// Add schema and validate document
xDoc.Schemas = schemas;
xDoc.Validate(eventHandler);
Definition of CallBack method.
private void ValidationCallBack(object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
throw new Exception(e.Message);
case XmlSeverityType.Warning:
throw new Exception(e.Message);
default: break;
}
}
XML input.
<Item>
<Id>Unique ID</Id>
<Date>2000-00-00 00:00:00</Date>
<Result>Data</Result>
</Item>
Schema definition.
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified"
elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Item">
<xs:complexType>
<xs:sequence>
<xs:element name="Id" />
<xs:element name="Date" />
<xs:element name="Result" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>