I'm running into real difficulties validating xml with xsd. I should prefix all of this and state up front, I'm new to xsd and validation, so I'm not sure if it's a code issue or an xml issue. I've been to xml api hell and back with the bajillion different options and think that I've found what would be the ideal strategy for validating xml with xsd. Note, my xml and xsd are coming from a database so I don't need to read anything from disk.
I've narrowed my problem down into a simple sample windows form app. It has a textbox for xsd (txtXsd), a textbox for xml (txtXml), a textbox for the result (txtResult), and a button to start the validation (btnValidate).
I'm using a sample xsd file from Microsoft.
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:bookstore-schema" elementFormDefault="qualified" targetNamespace="urn:bookstore-schema">
<xsd:element name="title" type="xsd:string" />
<xsd:element name="comment" type="xsd:string" />
<xsd:element name="author" type="authorName"/>
<xsd:complexType name="authorName">
<xsd:sequence>
<xsd:element name="first-name" type="xsd:string" />
<xsd:element name="last-name" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
I'm using the following code in my app.
private void btnValidate_Click (object sender, EventArgs e)
{
try
{
XmlTextReader reader = new XmlTextReader(txtXsd.Text, XmlNodeType.Document, new XmlParserContext(null, null, String.Empty, XmlSpace.None));
XmlSchema schema = XmlSchema.Read(reader, null);
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(schema);
XDocument doc = XDocument.Parse(txtXml.Text);
doc.Validate(schemas, ValidateSchema);
}
catch (Exception exception)
{
txtResult.Text += exception.Message + Environment.NewLine;
}
}
private void ValidateSchema (Object sender, ValidationEventArgs e)
{
txtResult.Text += e.Message + Environment.NewLine;
}
As a test, I put in valid xml but what I think should not conform to the xsd above.
<xml>
<bogusNode>blah</bogusNode>
</xml>
The result is nothing, no validation errors what soever. Any ideas?