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><bo ok
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 XmlValidatingRe ader, 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();
XmlNamespaceMan ager nsmgr = new XmlNamespaceMan ager(nt);
nsmgr.AddNamesp ace(String.Empt y, "urn:bookst ore-schema");
XmlParserContex t ctx = new XmlParserContex t(null, nsmgr, null,
XmlSpace.None);
XmlValidatingRe ader r = new XmlValidatingRe ader( xmlTxt,
XmlNodeType.Ele ment, ctx);
r.Schemas.Add( schema);
r.ValidationTyp e = ValidationType. Schema;
r.ValidationEve ntHandler += new ValidationEvent Handler (ValidationCall Back);
while (r.Read()){}
The schema was loaded from this:
<xsd:schema xmlns:xsd="http ://www.w3.org/2001/XMLSchema"
xmlns="urn:book store-schema"
elementFormDefa ult="qualified"
targetNamespace ="urn:bookst ore-schema">
<xsd:element name="bookstore " type="bookstore Type"/>
<xsd:complexTyp e name="bookstore Type">
<xsd:sequence maxOccurs="unbo unded">
<xsd:element name="book" type="bookType"/>
</xsd:sequence>
</xsd:complexType >
<xsd:complexTyp e name="bookType" >
<xsd:sequence >
<xsd:element name="title" type="xsd:strin g"/>
<xsd:element name="author" type="authorNam e"/>
<xsd:element name="price" type="xsd:decim al"/>
</xsd:sequence>
<xsd:attribut e name="genre" type="xsd:strin g"/>
</xsd:complexType >
<xsd:complexTyp e name="authorNam e">
<xsd:sequence >
<xsd:element name="first-name" type="xsd:strin g"/>
<xsd:element name="last-name" type="xsd:strin g"/>
</xsd:sequence>
</xsd:complexType >
</xsd:schema>