架构中的可选标签

时间:2013-07-24 16:14:03

标签: xml xml-parsing tags

如何创建条件标记,例如,在以下示例中, 我想要或标记。两者都无法出现在。只有其中一个。如何创建这样的XML模式?

Ex:
  <tool>
     <tool_name>xyz</tool_name>
  </tool>

  or 

 <tool>
    <tool_file>xyz.xml</tool_file>
 </tool>

2 个答案:

答案 0 :(得分:1)

为元素工具创建一个元素声明,其类型是一个名为toolType的复杂类型。这应该是一个复杂类型,内容模型是带有两个子节点的xs:choice,xs:element name =“tool_name”,xs:element name =“tool_file”。

答案 1 :(得分:0)

为您的示例引入了名称空间(可能比您想要的更复杂,但是很好的做法): 架构:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns="http://example.com/tools"
  targetNamespace="http://example.com/tools"
  elementFormDefault="qualified">

  <xsd:element name="tool">
    <xsd:complexType>
      <xsd:choice>
        <xsd:element name="tool_name" type="xsd:string" />
        <xsd:element name="tool_file" type="xsd:string" />
      </xsd:choice>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

这是有效的:

<tool xmlns="http://example.com/tools">
  <tool_name>hammer</tool_name>
</tool>

这不是:

<tool xmlns="http://example.com/tools">
  <tool_name>hammer</tool_name>
  <tool_file>hammer.png</tool_file>
</tool>