简体   繁体   中英

XSD (XML schema): Element must have one more more children

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM