使用 XSD 进行 XML 验证:如何避免关心元素的顺序? [英] XML validation with XSD: how to avoid caring about the sequence of the elements?
问题描述
我有以下 XSD 代码:
I have following XSD code:
<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>
这里的问题是:元素位置、multipleChoiceInput 等必须按照它们声明的顺序出现.我不希望这种情况发生,我希望那样,在验证过程中,序列不应该是相关的.我怎样才能做到这一点?
The problem here is: the elements location, multipleChoiceInput, etc. must appear in the same order they are declared. I don't want this to happen, I want that, in the validation process the sequence should not be relevant. How can I achieve this?
我尝试过的另一种可能性是:
Another possibility I've tried has been:
<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>
在这个例子中,顺序真的不再重要了,我可以拥有我想要的元素(所有"不允许我做的事情).但是我仍然有 min- 和 maxOccurs 的问题.在这个例子中,我可以有尽可能多的图片输入",这与我想要 0 或 1 的约束有何不同.
In this example, the sequence really does not matter anymore, and I can have so much elements as I want (what "all" would not allow me to do). But I still have the Problem with the min- and maxOccurs. In this example, I could have so many "pictureInput"s as possible, what is againt the constraint that I would like to have either 0 or 1.
非常感谢您的帮助!
推荐答案
<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>
注意:我已将序列"更改为全部"
NOTE: I have changed "sequence" to "all"
序列强制顺序(如定义).如果顺序无关紧要,则全部使用.
Sequence forces order (as defined). if order doesn't matter then all is used.
如果元素出现多次的机会,则可以使用 xsd:any.
If there are chances of element occurence more than once then xsd:any can be used.
<xsd:complexType name="questions">
<xsd:sequence>
<xsd:any minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
您可以在以下链接中找到 xsd:any 的详细信息:
You can find details of xsd:any at following link:
https://www.w3schools.com/xml/schema_complex_any.asp
这篇关于使用 XSD 进行 XML 验证:如何避免关心元素的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!