问题
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