如何在XSD中定义complexType,它可以具有属性和具有相同名称的元素?
例如:
<configuration>
<configure name="variable1" value="val1"/>
<configure name="variableList">
<value>val1</value>
<value>val2</value>
<value>val3</value>
</configure>
</configuration>
怎么能为此写一个XSD?
答案 0 :(得分:2)
定义具有与元素同名的属性的元素没有什么特别之处。以下XSD将验证您的XML:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="configuration">
<xs:complexType>
<xs:sequence>
<xs:element name="configure"
minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="value" type="xs:string"
minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string"/>
<xs:attribute name="value" type="xs:string"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
如果您希望configure
的类型根据name
的值而变化,请使用conditional type assignment(需要XSD 1.1),或者更好的是,只需区分元素名称本身(适用于XSD 1.0和1.1):
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="try.xsd">
<configure name="variable1" value="val1"/>
<configureList name="variable2">
<value>val1</value>
<value>val2</value>
<value>val3</value>
</configureList>
</configuration>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="configuration">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="configure"
minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="name" type="xs:string"/>
<xs:attribute name="value" type="xs:string"/>
</xs:complexType>
</xs:element>
<xs:element name="configureList"
minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="value" minOccurs="0"
maxOccurs="unbounded"
type="xs:string"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string"/>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>