给出这样的
XML布局,我试图创建一个XSD模式来验证它.
<RootNode> <ChildA /> <ChildC /> <ChildB /> <ChildB /> <ChildA /> </RootNode>
要求如下:
> ChildA,ChildB和ChildC可能以任何顺序发生. (< xs:sequence>不合适)
> ChildA是强制性的,但可能会发生多次.
> ChildB是可选的,可能会发生多次.
> ChildC是可选的,只能发生一次.
我通常用于创建无序列表的技术是使用< xs:choice maxOccurs =“unbounded”>然而,列表中的每个可能的节点,我无法在ChildA上创建minOccurs =“1”约束,而在ChildC上无法创建maxOccurs =“1”约束. (选择的发生次数优先于这些元素的出现次数).
<xs:element name="RootNode"> <xs:complexType> <xs:choice minOccurs="1" maxOccurs="unbounded"> <xs:element name="ChildA" minOccurs="1"/> <xs:element name="ChildB" /> <xs:element name="ChildC" maxOccurs="1"/> </xs:choice> </xs:complexType> </xs:element>
不是一个简单的,但似乎可行.这里的难点在于,模式定义必须是确定性的.我使用的方法是通过绘制有限状态自动机来形象化问题,然后编写与自动机对应的正则表达式.它听起来并不复杂.不过,使用其他一些验证系统可能会提供更简单的答案.
原文链接:https://www.f2er.com/xml/292865.html我做了一些测试,但是错过了一些特殊情况很容易.如果发现错误,请给予评论.
…这里是代码:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" > <!-- Schema for elements ChildA,ChildB and ChildC The requirements are as follows: * ChildA,ChildB and ChildC may occur in any order. * ChildA is mandatory but may occur multiple times. * ChildB is optional and may occur multiple times. * ChildC is optional and may occur once only. --> <xsd:element name="root"> <xsd:complexType> <xsd:sequence> <xsd:element name="ABC-container" type="ABC" maxOccurs="unbounded"/> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:complexType name="ABC"> <xsd:sequence> <xsd:element name="ChildB" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/> <xsd:choice> <xsd:sequence maxOccurs="1"> <xsd:element name="ChildC" type="xsd:string"/> <xsd:element name="ChildB" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/> <xsd:element name="ChildA" type="xsd:string"/> <xsd:sequence minOccurs="0" maxOccurs="unbounded"> <xsd:element name="ChildA" type="xsd:string" minOccurs="0"/> <xsd:element name="ChildB" type="xsd:string" minOccurs="0"/> </xsd:sequence> </xsd:sequence> <xsd:sequence maxOccurs="1"> <xsd:element name="ChildA" type="xsd:string" minOccurs="1"/> <xsd:sequence minOccurs="0" maxOccurs="unbounded"> <xsd:element name="ChildA" type="xsd:string" minOccurs="0"/> <xsd:element name="ChildB" type="xsd:string" minOccurs="0"/> </xsd:sequence> <xsd:sequence minOccurs="0" maxOccurs="1"> <xsd:element name="ChildC" type="xsd:string"/> <xsd:sequence minOccurs="0" maxOccurs="unbounded"> <xsd:element name="ChildA" type="xsd:string" minOccurs="0"/> <xsd:element name="ChildB" type="xsd:string" minOccurs="0"/> </xsd:sequence> </xsd:sequence> </xsd:sequence> </xsd:choice> </xsd:sequence> </xsd:complexType> </xsd:schema>