Hi,
I'm trying to validate my xml against a xsd but I can't get it to work.
Originally, I wanted to validate an xml string but since I didn't get that
to work I tried to validate an xml file instead. Didn't work either.
Actuallty, the xml gets loaded but there are no events raised that says my
xml is incorrect!
I'm using .NET 2.0 and my code is listed below. ALL help is appreciated!
Thanks!
/Jonny
void myValidate()
{
FileStream fs = File.Open(@"C:\Test.xml", FileMode.Open);
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null,@"C:\Test.xsd");
settings.ValidationType = ValidationType.Schema; //this line is
neccessary for validation to work
settings.ValidationEventHandler += new
ValidationEventHandler(rs_ValidationEventHandler);
XmlReader xreader = XmlReader.Create(fs, settings);
XmlDocument xdoc = new XmlDocument();
xdoc.Load(xreader);
fs.Close();
}
void rs_ValidationEventHandler(object sender, ValidationEventArgs e)
{
Debug.WriteLine("e.Message: " + e.Message);
}
Schema:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="urn:bookstore-schema" elementFormDefault="qualified"
targetNamespace="urn:bookstore-schema">
<xsd:element name="bookstore" type="bookstoreType" />
<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:complexType name="bookstoreType">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="book" type="bookType" />
<xsd:element ref="comment" minOccurs="0" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="bookType">
<xsd:sequence>
<xsd:element name="title" type="xsd:string" />
<xsd:element ref="author" />
<xsd:element name="price" type="xsd:decimal" />
</xsd:sequence>
<xsd:attribute name="genre" type="xsd:string" />
</xsd:complexType>
</xsd:schema>
xml:
<?xml version="1.0" encoding="utf-8"?>
<root xmlns="http://myns/slidesdemo"
xmlns:rv="http://myns/slidesdemo/reviewdate">
<session name="All about XML">
<slide>
<slide position="1">
<title>Agenda</title>
<rv:reviewed>2004-05-10T00:00:00</rv:reviewed>
</slide>
<slide position="2">
<title>Introduction</title>
<rv:reviewed>2003-10-22T00:00:00</rv:reviewed>
</slide>
<ILLEGAL_NODE>
<NONSENSE>NONSENSE</NONSENSE>
</ILLEGAL_NODE>
<slide position="3">
<title>Code Examples</title>
<rv:reviewed>2004-03-02T00:00:00</rv:reviewed>
</slide>
</slide>
</session>
</root>