开发者

Require that an element has another element as a descendant

Is there a way in an xsd schema to require that an element have another element somewhere as a descendant?

For example, element parent requires a descendant desc. This is valid:

<parent>
  <a>
   <b>
     <desc></desc>
   </b>
  </a开发者_运维知识库>
</parent>

As is this:

<parent>
  <c>
    <desc></desc>
  </c>
</parent>

but this isn't:

<a>
  <parent>
    <b/>
  </parent>
</a>

The potential child elements for parent are many and complicates, so it would be difficult to enumerate every possible valid configuration.

Something like the key/selector schema elements seems like it would work, where I could provide an xpath expression defining the valid locations for desc element, but all of the examples I've found are aimed at matching up the value of attributes.


No, (almost) all XML Schema validation is shallow, called "local" in the spec. Here's one excerpt that emphasizes type validation as "local" validation.

Element Validated by Type If an element information item is ·valid· with respect to a ·type definition· as per Element Locally Valid (Type) (§3.3.4), [it is marked as] ·validated·.

The only exception is for the identity constraints like uniqueness and key-references which have a broad scope in an XML document but narrow uses.


I don't know if XSD supports what you are trying to do, but there is a work-around.

You could do complex validations with a two-step process:

  • First simply use your XSD schema for basic validation
  • Next use an XSLT which does more complex validations, and outputs the result of that validation

This may not plug in well to whatever framework you are working with, but might work well for (partially) custom code. It also has the advantage (over doing the extra validations in code) that you can publish both documents.

From a quick google search, one effort towards this end is Schematron. It actually foregos XSD entirely, and just uses XSLT. It appears to be a published standard:

  • http://www.schematron.com/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜