简体   繁体   English

xsd验证xml可选子元素

[英]xsd validate xml optional sub-elements

I have been trying to construct an XSD file to validate some xml 我一直试图构造一个XSD文件来验证一些xml

XSD Example XSD示例

<xs:element name="person" type="persontype"/>
<xs:complexType name="persontype">
  <xs:sequence>
    <xs:element name="firstname" type="xs:string"/>
    <xs:element name="lastname" type="xs:string"/>
  </xs:sequence>
</xs:complexType>

XML Example XML范例

<persontype>
  <firstname/>
  <lastname/>
</persontype>

How can I construct the xsd to require that the 'firstname' is mandatory, and the 'lastname' is not even necessary for the xml to be valid, and that the sequence does not have to be in order, so long as the hierarchy is respected? 我如何构造xsd以要求“ firstname”是强制性的,而对于XML来说,“ lastname”甚至不是必需的,并且只要层次结构是,就不必按顺序排列。受尊重?

End Result of XMLs which could be encountered, and which I would like to be considered valid according to my final xsd. 可能遇到的XML最终结果,根据我的最终xsd,我希望它被认为是有效的。

Valid Scenario 1 有效方案1

<persontype>
  <firstname/>
</persontype>

Valid Scenario 2 有效方案2

<persontype>
  <lastname/>
  <firstname/>
</persontype>

Appreciate your time with the help. 在帮助下感谢您的时间。

I've adapted this from the XML Schema tutorial on indicators : 我已经根据指标XML Schema教程对此进行了调整:

<xs:element name="person">
  <xs:complexType>
    <xs:all>
      <xs:element name="firstname" type="xs:string"/>
      <xs:element name="lastname" type="xs:string" minOccurs="0"/>
    </xs:all>
  </xs:complexType>
</xs:element>

If you use the all indicator, the sequence of your elements can be arbitrary, but by default each element has to occur exactly one time. 如果使用all指示符,则元素的顺序可以是任意的,但是默认情况下,每个元素必须恰好发生一次。 To make lastname optional, you can change the default by providing the minOccurs indicator and setting it to zero. 要使姓氏为可选,可以通过提供minOccurs指示器并将其设置为零来更改默认名称。

This will allow you to optionally specify a single lastname per person, with any order of elements. 这将允许您有选择地为每个人指定一个姓氏,并使用任意顺序的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM