gpt4 book ai didi

具有相同名称但属性值不同的元素序列的 XML 模式?

转载 作者:数据小太阳 更新时间:2023-10-29 01:45:24 26 4
gpt4 key购买 nike

如何为这样的实例文​​档指定 XML 模式:

<productinfo>
<!-- other stuff -->
<informationset type="Manufacturer">
<!-- content not relevant -->
</informationset>
<informationset type="Ingredients">
<!-- content not relevant -->
</informationset>
</productinfo>

也就是说,“productinfo”元素包含两个“informationset”子元素的序列,第一个元素有 @type="Manufacturer",第二个元素有 @type="Ingredients"?

最佳答案

注意正如 Serge 所指出的,这个答案是不正确的。

使用 xerces 进行测试会出现此错误:type.xsd:3:21: cos-element-consistent: Error for type '#AnonType_productinfo'。名称为“informationset”、具有不同类型的多个元素出现在模型组中。 cos-element-consistent 的规范中有更多详细信息.

但是有一个解决方案,类似于下面 Marc 的回答,但仍然使用类型。如果它们在由其他类型扩展的父类(super class)型的 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# 中的多态类列表。但是您至少可以指定整个列表的确切长度(如果您愿意)。

例如,我将上面的示例限制为正好两个元素,但未设置顺序(即 Manufacturer 可能是第一个,或者 Ingredients 可能是第一个);并且重复次数未设置(即它们可以都是制造商,或者都是成分,或者两者之一)。


您可以使用 XML 架构类型,如:

<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% 清楚确切原因 - 有人知道规范的相关部分吗?

关于具有相同名称但属性值不同的元素序列的 XML 模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/827051/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com