我有以下XML:
<items>
<item type="simple">some text</item>
<item type="complex"><b>other text</b></item>
</items>
我可以用DTD定义“item”元素,如:
<!ELEMENT item (#PCDATA|b)*>
如何使用XML Schema(XSD)定义它?
答案 0 :(得分:0)
XML模式具有这些膨胀抽象类型,只要在实际XML中的type属性上使用xsi前缀不会打扰您,就可以轻松实现这一点。您可以按如下方式定义上面的内容:
<!--items element-->
<xs:element name="items">
<xs:complexType>
<xs:sequence>
<xs:element ref="item" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
</xs:element>
<!--individual item element-->
<xs:element name="item" type="item" />
<!--make the item type abstract so you're forced to declare its type in the XML file-->
<xs:complexType name="item" abstract="true" />
<!--declare your simple type - mixed content is so that you can have text in a complex type-->
<xs:complexType name="simple">
<xs:complexContent mixed="true">
<xs:extension base="item">
</xs:extension>
</xs:complexContent>
</xs:complexType>
<!--declare your complex type-->
<xs:complexType name="complex">
<xs:complexContent>
<xs:extension base="item">
<!--define the stuff that can go into that complex element-->
<xs:sequence>
<xs:element name="b" type="xs:string" />
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
您生成的XML将如下所示:
<items xmlns="your-namespace" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<item xsi:type="simple">some text</item>
<item xsi:type="complex">
<b>other text</b>
</item>
</items>