XML Schema用于具有相同名称但属性值不同的元素序列?
如何为实例文档指定
XML模式,如下所示:
<productinfo> <!-- other stuff --> <informationset type="Manufacturer"> <!-- content not relevant --> </informationset> <informationset type="Ingredients"> <!-- content not relevant --> </informationset> </productinfo> 也就是说,“productinfo”元素包含两个“信息集”子节点的序列,第一个具有@type =“Manufacturer”,第二个具有@type =“Ingredients”?
注意这个答案是不正确的,正如塞尔指出的那样.
使用xerces进行测试会出现此错误:type.xsd:3:21:cos-element-consistent:类型为“#AnonType_productinfo”的错误.名称为“informationset”且具有不同类型的多个元素显示在模型组中. cos-element-consistent的规格中有更多细节. 但是有一个解决方案,类似于下面Marc的答案,但仍然使用类型.如果它们位于超类型的minOccurs / maxOccurs列表中,则可以多次出现相同的不同类型,这些列表由其他类型扩展.也就是说,就像java或C#中的多态类列表一样.这克服了上面的问题,因为虽然该元素名称可以在xml中出现多次,但它只在xsd中出现一次. 这是示例xsd和xml – 这次用xerces测试!: <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="productinfo"> <xs:complexType> <xs:sequence> <xs:element name="informationset" type="supertype" minOccurs="2" maxOccurs="2"/> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="supertype"> </xs:complexType> <xs:complexType name="Manufacturer"> <xs:complexContent> <xs:extension base="supertype"> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="Ingredients"> <xs:complexContent> <xs:extension base="supertype"> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema> <productinfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <informationset xsi:type="Manufacturer"></informationset> <informationset xsi:type="Ingredients"></informationset> </productinfo> 注意:您无法控制不同类型的顺序,或每种类型出现的次数(每种类型可能出现一次,多次或根本不出现) – 就像java或C#中的多态类列表一样.但是你至少可以指定整个列表的确切长度(如果你愿意). 例如,我将上面的例子限制为恰好两个元素,但未设置顺序(即制造商可以是第一个,或者成分可以是第一个);并且没有设置重复次数(即它们既可以是制造商,也可以是两种成分,或者每种都是其中之一). 您可以使用XML Schema类型,如下所示: <productinfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <informationset xsi:type="Manufacturer"></informationset> <informationset xsi:type="Ingredients"></informationset> </productinfo> XSD为每个复杂类型定义了: <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="productinfo"> <xs:complexType> <xs:sequence> <xs:element name="informationset" type="Manufacturer"/> <xs:element name="informationset" type="Ingredients"/> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="Manufacturer"> </xs:complexType> <xs:complexType name="Ingredients"> </xs:complexType> </xs:schema> 这是xsi:type的特例.通常,不要认为您可以指定属性在同一个元素的元素中具有不同的值,因为它们是同一元素的不同定义. 我不是100%明确的原因 – 任何人都知道规范的相关部分? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |