XSD for recursive element definition

荒凉一梦 提交于 2019-12-24 11:45:09

问题


I have a case where I need an element to able to either nest itself or have other elements.

Something like this should be valid:

<root>
  <rule condition="...">
    <rule condition="...">
      <setting>...</setting>
    </rule>
  </rule>
  <rule condition="...">
    <setting>...</setting>
  </rule>
</root>

But this should not be valid:

<root>
  <rule condition="...">
    <rule condition="...">
      <setting>...</setting>
    </rule>
    <setting>...</setting>
    <setting>...</setting>
  </rule>
</root>

If I understand XSD correctly this should do the job but it doesn't. What am I doing wrong?

<xs:complexType name="RuleType">
    <xs:choice>
        <xs:element name="rule" minOccurs="1" 
                    maxOccurs="unbounded" type="RuleType" />
        <xs:element name="setting" minOccurs="1"
                    maxOccurs="unbounded" type="xs:string" />
    </xs:choice>
    <xs:attribute name="condition" type="xs:string" use="required"/>
</xs:complexType>

回答1:


This XSD will allow your first example XML but not your second:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="rule" type="RuleType"/>

  <xs:complexType name="RuleType">
    <xs:choice>
      <xs:element name="setting" minOccurs="1" maxOccurs="unbounded" />
      <xs:element ref="rule" minOccurs="1" maxOccurs="unbounded" />
    </xs:choice>
    <xs:attribute name="condition" use="required"/>
  </xs:complexType>

</xs:schema>

Read the XSD like this: Each rule can consist of either one or more setting elements or one or more other rule elements (recursively).



来源:https://stackoverflow.com/questions/28775059/xsd-for-recursive-element-definition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!