I need to validate XML fragment against XSD schema. The main issue is that
xml fragment does not contain refrence to schema, but I want to force the
validation against the schema I have in XmlSchema object.
The scenario is as follows:
I have
string fragment;
containing xml fragment, e.g. something like
"<bookstore><book
genre="novel"><title>Abc</title><author><first-name>A</first-name><last-name
B</last-name></author><price>8.99</price></book></bookstore>"
but this xml is just fragment of larger xml document received from third
party;
and
XmlSchema schema;
containing loaded XSD of bookstore.
I need code snippet to perform validation of fragment against schema.
Thanks,
eXavier
I played a little with XmlValidatingReader, but I am no guru in XSDs and
..NET System.XML namespace, so I don't much understand what namespaces to set
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
nsmgr.AddNamespace(String.Empty, "urn:bookstore-schema");
XmlParserContext ctx = new XmlParserContext(null, nsmgr, null,
XmlSpace.None);
XmlValidatingReader r = new XmlValidatingReader( xmlTxt,
XmlNodeType.Element, ctx);
r.Schemas.Add( schema);
r.ValidationType = ValidationType.Schema;
r.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
while (r.Read()){}
The schema was loaded from this:
<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:complexType name="bookstoreType">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="book" type="bookType"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="bookType">
<xsd:sequence>
<xsd:element name="title" type="xsd:string"/>
<xsd:element name="author" type="authorName"/>
<xsd:element name="price" type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="genre" type="xsd:string"/>
</xsd:complexType>
<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>