Validating an XML document fragment against XML schema

Posted by shylent on Stack Overflow See other posts from Stack Overflow or by shylent
Published on 2010-04-17T12:42:28Z Indexed on 2010/04/17 12:53 UTC
Read the original article Hit count: 1292

Terribly sorry if I've failed to find a duplicate of this question.

I have a certain document with a well-defined document structure. I am expressing that structure through an XML schema.

That data structure is operated upon by a RESTful service, so various nodes and combinations of nodes (not the whole document, but fragments of it) are exposed as "resources". Naturally, I am doing my own validation of the actual data, but it makes sense to validate the incoming/outgoing data against the schema as well (before the fine-grained validation of the data).

What I don't quite grasp is how to validate document fragments given the schema definition.

Let me illustrate:

Imagine, the example document structure is:

<doc-root>
  <el name="foo"/>
  <el name="bar"/>
</doc-root>

Rather a trivial data structure. The schema goes something like this:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="doc-root">
    <xsd:complexType>
        <xsd:sequence>
          <xsd:element name="el" type="myCustomType" />
        </xsd:sequence>
    </xsd:complexType>
  </xsd:element>

  <xsd:complexType name="myCustomType">
    <xsd:attribute name="name" use="required" />
  </xsd:complexType>
</xsd:schema>

Now, imagine, I've just received a PUT request to update an 'el' object. Naturally, I would receive not the full document or not any xml, starting with 'doc-root' at its root, but the 'el' element itself. I would very much like to validate it against the existing schema then, but just running it through a validating parser wouldn't work, since it will expect a 'doc-root' at the root.

So, again, the question is, - how can one validate a document fragment against an existing schema, or, perhaps, how can a schema be written to allow such an approach.

Hope it made sense.

© Stack Overflow or respective owner

Related posts about Xml

Related posts about xml-schema