考虑以下XML样本文档,该文档包含具有键值对的变量,也可以是递归:
<?xml version="1.0" encoding="UTF-8"?>
<environments>
<variable>
<key>Variable 1</key>
<value>Value</value>
</variable>
<variable>
<value>B</value>
<key>Variable 2</key>
</variable>
<variable>
<value></value>
<key>Variable 2</key>
</variable>
<variable>
<key>Variable 2</key>
<value>
<variable>
<key>Foo</key>
<value>Bar</value>
</variable>
</value>
</variable>
<variable>
<key>Variable 2</key>
<value>
<variable>
<key>Foo</key>
<value>
<variable>
<key>Foo</key>
<value>Bar</value>
</variable>
</value>
</variable>
</value>
</variable>
</environments>
我想创建一个可以验证此结构的XML模式:零或更多variable
元素,key
元素仅是字符串,value
元素仅是字符串或嵌套变量。
到目前为止,我想到了:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1">
<!-- Element: Environments -->
<xs:element name="environments">
<xs:complexType>
<xs:sequence maxOccurs="unbounded">
<xs:element ref="variable"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<!-- Element: variable_type -->
<xs:element name="variable">
<xs:complexType>
<xs:all>
<xs:element ref="key"/>
<xs:element ref="value"/>
</xs:all>
</xs:complexType>
</xs:element>
<!-- Element: key -->
<xs:element name="key" type="xs:string"/>
<!-- Element: value -->
<xs:element name="value">
<xs:complexType mixed="true">
<xs:sequence>
<xs:choice>
<xs:element minOccurs="0" maxOccurs="unbounded" ref="variable"/>
</xs:choice>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
此模式适用于我的示例文档。但是,我非常不确定涉及值元素:<xs:complexType mixed="true">
。这意味着像这样的variable
元素也将被视为有效(嵌套variable
元素之前的额外foo
字符):
<variable>
<key>Variable 2</key>
<value>
foo
<variable>
<key>Foo</key>
<value>Bar</value>
</variable>
</value>
</variable>
我的问题:我如何确定value
元素是另一个variable
元素(复杂类型),或者只是字符串?
XSD中的混合内容实际上仅适用于叙事文本文档。除了使用XSD 1.1断言外,您可以对混合内容强加的有效约束很少。最好避免使用这种内容模型。