Abstract restriction
W3CChina.org论坛上看到一个帖子有人问Attribute怎么实现choice.即Element名称一样,但是Attribute是可选择的,如果用element的choice,但是不能写同样的element名字,因为会有冲突.
Attribute没有 choice的属性,Attribute必须要依赖于Element存在,我换了一种方法变通实现.
1.Schema
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="ChoiceAttribute">
<xs:annotation>
<xs:documentation>Att</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence maxOccurs="unbounded">
<xs:element name="Nodes" type="NodeType"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="NodeType" abstract="true">
<xs:sequence>
<xs:element name="Node" type="xs:string"/>
</xs:sequence>
<xs:attributeGroup ref="ABCGroup"/>
<xs:attribute name="C"/>
</xs:complexType>
<xs:attributeGroup name="ABCGroup">
<xs:attribute name="A" type="xs:string" use="optional"/>
<xs:attribute name="B" type="xs:string" use="optional"/>
</xs:attributeGroup>
<xs:complexType name="NodeTypeA">
<xs:complexContent>
<xs:restriction base="NodeType">
<xs:sequence>
<xs:element name="Node" type="xs:string"/>
</xs:sequence>
<xs:attribute name="A" type="xs:string" use="optional"/>
<xs:attribute name="B" type="xs:string" use="prohibited"/>
<xs:attribute name="C" use="prohibited"/>
</xs:restriction>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="NodeTypeB">
<xs:complexContent>
<xs:restriction base="NodeType">
<xs:sequence>
<xs:element name="Node" type="xs:string"/>
</xs:sequence>
<xs:attribute name="B" type="xs:string" use="optional"/>
<xs:attribute name="A" type="xs:string" use="prohibited"/>
<xs:attribute name="C" use="prohibited"/>
</xs:restriction>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="NodeTypeC">
<xs:complexContent>
<xs:restriction base="NodeType">
<xs:sequence>
<xs:element name="Node" type="xs:string"/>
</xs:sequence>
<xs:attribute name="A" type="xs:string" use="prohibited"/>
<xs:attribute name="B" type="xs:string" use="prohibited"/>
<xs:attribute name="C" type="xs:string" use="required"/>
</xs:restriction>
</xs:complexContent>
</xs:complexType>
</xs:schema>
2.Sample XML
<?xml version="1.0" encoding="UTF-8"?>
<!--Sample XML file generated by XMLSpy v2007 sp1 (http://www.altova.com)-->
<ChoiceAttribute xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ChoiceAttribute.xsd">
<Nodes xsi:type="NodeTypeA" A="String">
<Node>String</Node>
</Nodes>
<Nodes xsi:type="NodeTypeB" B="String">
<Node>String</Node>
</Nodes>
<Nodes xsi:type="NodeTypeC" C="String">
<Node>String</Node>
</Nodes>
</ChoiceAttribute>
通过继承方式来实现,不过需要在xml instance里添加属性xsi:type 来标记具体的类型
只是一种实现方式,比较麻烦。