gpt4 book ai didi

XSD 扩展类型,并在顶部和底部添加字段

转载 作者:行者123 更新时间:2023-12-01 04:38:21 25 4
gpt4 key购买 nike

我有以下 XSD(为了问这个问题):

  <xsd:complexType name="BaseType" abstract="true">
<xsd:sequence>
<xsd:element name="field1" type="xsd:string"/>
<xsd:element name="field2" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>

<xsd:complexType name="ExtendedType">
<xsd:complexContent>
<xsd:extension base="tns:BaseType">
<xsd:sequence>
<xsd:element name="fieldA" type="xsd:string"/>
<xsd:element name="fieldB" type="xsd:string"/>
</xsd:sequence>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>

<xsd:element name="extendedType" type="tns:ExtendedType"/>

这允许一个 XML 文件如下:

<extendedType>
<field1>hello</field1>
<field2>world</field2>
<fieldA>aaa</fieldA>
<fieldB>bbb</fieldB>
</extendedType>

即在BaseType的底部增加了两个新闻字段fieldA和fieldB。

有没有办法扩展 BaseType,但是在顶部插入 fieldA,在底部插入 fieldB?这样就可以了吗?

<extendedType>
<fieldA>aaa</fieldA>
<field1>hello</field1>
<field2>world</field2>
<fieldB>bbb</fieldB>
</extendedType>

以及如何使 JAXB 按预期工作?

最佳答案

http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/structures.html#Complex_Type_Definition

A complex type which extends another does so by having additional content model particles at the end of the other definition's content model, or by having additional attribute declarations, or both.

  • Note: This specification allows only appending, and not other kinds of extensions. This decision simplifies application processing required to cast instances from derived to base type. Future versions may allow more kinds of extension, requiring more complex transformations to effect casting.

因此,在扩展类型时,字段只会添加到底部。

黑客攻击:扩展 类型的字段出现在顶部。即添加到扩展类型的字段被添加到顶部。因此,您可以拥有三个级别的类型:顶部“虚拟”级别(用于顶部字段)、具有您要继承的字段的中间级别和底部级别(用于底部字段)。导入它的模式将定义底层 - 和 redefine顶层。这将使您能够在顶部和底部添加字段。 问题 是它还会为扩展它的所有其他类型重新定义顶层...所以这些额外的字段将随处可见,这可能不是您想要的。

其他替代方案包括:避免扩展机制,而是使用 substitution groups (但这些需要不同的元素名称);或在元素内创建您自己的多态性 ( <choice> ) 和继承 ( <group ref="..."/> 在顶部和底部) - 但请注意,每个选择都必须唯一开始或违反 UPA 规则(因为它们不会被区分属性,如 xsi:type )。

编辑 我看到另一个答案已经涵盖了这一点我已经输入了所有这些内容,还有一些额外的建议,所以我不妨保留它。

关于XSD 扩展类型,并在顶部和底部添加字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13681969/

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