Mathieu
Mathieu

Reputation: 3083

Validate an XML-file with only a part of an XSD-file in C#

I have a XSD-file that has a lot of elements in it. With a only a part of that XSD-file I need to validate an incoming XML-file.

For example:

This is the valid XML

<in attr1="9" attr2="0" attr3="0" />

This is the XSD-file. Only the element named "In" under the element "FindPerson" is necessary to validate the XML-file.

<xs:element name="WS">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="ELEMENT1">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="FindPerson">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element name="In">
                                            <xs:complexType>
                                                <xs:attribute name="attr1" type="xs:int"/>
                                                <xs:attribute name="attr2" type="xs:boolean" use="optional" default="0"/>
                                                <xs:attribute name="attr3" type="xs:boolean" use="optional" default="0"/>
                                            </xs:complexType>
                                        </xs:element>

...

Is there a way to validate a XML file with only a part of an XSD-file in C#?

Upvotes: 1

Views: 561

Answers (2)

Petru Gardea
Petru Gardea

Reputation: 21638

This is actually possible with a little bit of work on your part, and assuming that indeed your XSD is authored using the Russian Doll style (all content nested), as kind of hinted by your truncated XSD.

An easy way would be to follow these steps:

  • read the original XSD as plain XML file; find the node you wish to use, using XPath, and hold on to it.
  • Create a new XML document; create the document element to be the schema, with the appropriace namespace; create (or not) an attribute for targetNamespace with the appropriate value; same for elementFormDefault;
  • Deep clone and copy your In node definition under the schema element you created above
  • Create an XmlNodeReader from your newly created document element node.
  • Use the XmlSchema.Read(nodeReader) to read the schema
  • Compile using an XmlSchemaSet; if successful, use that schema set to validate.

The idea here is to create the schema that you need, in memory, on the flight. If the content model is more complicated (not a Russian Doll), then things could easily compound to a point where it'll not be feasible.

Upvotes: 1

Jirka Hanika
Jirka Hanika

Reputation: 13529

You will want to restructure your XSD. Make all the elements siblings (on the top level). Use element ref=... to reference one from the other as you define their relations. Then your XSD will be able to verify any top level element.

Upvotes: 0

Related Questions