问题描述:

Let's say I have an XML element like this, and I'm trying to write the XSD for this element:

<foo name="bar">

...

</foo>

The rules for this element are:

  • Its name is "foo"
  • It has an attribute with name "bar"
  • Its "bar" attribute value is a string
  • It must have one or more children

This XSD encapsulate all of the rules except the last:

How do I specify the last rule—that the element must have children?

网友答案:

Use the <xs:any> element to allow any elements as child content.

Example code to match your rules:

<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="foo">
    <xs:complexType>
      <xs:sequence>
        <xs:any minOccurs="1" maxOccurs="unbounded" />
      </xs:sequence>
      <xs:attribute name="bar" type="xs:string" />
    </xs:complexType>
  </xs:element>
</xs:schema>

You can control the allowed elements and the validation of foo's children by using namespace and processContents attributes with that <xs:any> element.

网友答案:

If you don't know the type names then you are out of luck. There is nothing in XSD which says "Must have child elements". However, if you are happy to constrain your child elements within a "children-wrapper" then something like this should work for you:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="foo">
    <xs:complexType>
      <xs:sequence>
        <xs:element minOccurs="1" name="children" type="xs:anyType" />
      </xs:sequence>
      <xs:attribute name="bar" type="xs:string" />
    </xs:complexType>
  </xs:element>
</xs:schema>

Of course this means you have to use the xs:anyType type.

相关阅读:
Top