使用XSD进行XML验证:如何避免关注元素序列?

jcb*_*ges 37 xml xsd xml-validation

我有以下XSD代码:

<xsd:complexType name="questions">
    <xsd:sequence>
        <xsd:element name="location" type="location"/>
        <xsd:element name="multipleChoiceInput" type="multipleChoiceInput" minOccurs="0" maxOccurs="unbounded"/>
        <xsd:element name="textInput" type="textInput" minOccurs="0" maxOccurs="unbounded"/>
        <xsd:element name="pictureInput" type="pictureInput" minOccurs="0"/>
    </xsd:sequence>
</xsd:complexType>
Run Code Online (Sandbox Code Playgroud)

这里的问题是:元素位置,multipleChoiceInput等必须以它们声明的相同顺序出现.我不希望这种情况发生,我希望在验证过程中序列不应该相关.我怎样才能做到这一点?

我尝试过的另一种可能性是:

<xsd:complexType name="questions">

        <xsd:choice maxOccurs="unbounded">   
            <xsd:element name="location" type="location"/>  
            <xsd:element name="multipleChoiceInput" type="multipleChoiceInput" minOccurs="0" maxOccurs="unbounded"/>
            <xsd:element name="textInput" type="textInput" minOccurs="0" maxOccurs="unbounded"/>
            <xsd:element name="pictureInput" type="pictureInput" minOccurs="0" maxOccurs="1"/>
        </xsd:choice>            

</xsd:complexType>
Run Code Online (Sandbox Code Playgroud)

在这个例子中,序列真的无关紧要,我可以拥有我想要的那么多元素("所有"不允许我做什么).但我仍然遇到min-和maxOccurs的问题.在这个例子中,我可以拥有尽可能多的"pictureInput",但是我希望拥有0或1的约束.

非常感谢您的帮助!

YoK*_*YoK 47

<xsd:complexType name="questions">
    <xsd:all>
        <xsd:element name="location" type="location"/>
        <xsd:element name="multipleChoiceInput" type="multipleChoiceInput"/>
        <xsd:element name="textInput" type="textInput"/>
        <xsd:element name="pictureInput" type="pictureInput"/>
    </xsd:all>
</xsd:complexType>
Run Code Online (Sandbox Code Playgroud)

注意:我已将"序列"更改为"全部"

序列强制顺序(如定义).如果订单无关紧要则全部使用.

如果元素出现的可能性不止一次,则可以使用xsd:any.

<xsd:complexType name="questions">
    <xsd:sequence>
        <xsd:any minOccurs="0"/>
    </xsd:sequence>
</xsd:complexType>
Run Code Online (Sandbox Code Playgroud)

您可以在以下链接中找到xsd:any的详细信息:

https://www.w3schools.com/xml/schema_complex_any.asp

  • 感谢你回答YoK,但是"all"不能在我的情况下使用,因为"all"要求元素只出现在ONCE(min-和maxOccurs只能接受值0和1). (2认同)

CD *_*sen 19

我讨论的时间有点晚,但我遇到了同样的问题并找到了解决方案:

<xsd:complexType name="questions">
    <xsd:choice maxOccurs="unbounded">
        <xsd:element name="location" type="location"/>
        <xsd:element name="multipleChoiceInput" type="multipleChoiceInput"/>
        <xsd:element name="textInput" type="textInput"/>
        <xsd:element name="pictureInput" type="pictureInput"/>
    </xsd:choice>
</xsd:complexType>
Run Code Online (Sandbox Code Playgroud)

关键是将xs:choice与maxOccurs ="unbounded"结合起来.如果您只使用xs:all,则允许每个句点中的一个.

编辑添加:虽然xs:any将起作用,但它不会将您的选择限制为逐项列出的四个元素.它将允许任何东西,这几乎违背了模式的目的.