gpt4 book ai didi

java - schemagen:如何共享类,而不是它们的命名空间?

转载 作者:行者123 更新时间:2023-11-30 09:17:27 25 4
gpt4 key购买 nike

我有两个顶级类(class),它们按组成共享第三个类(class)。示例:

@XmlRootElement
@XmlType(namespace = "http://example.com/foo")
public class Foo {
public Shared shared;
}

@XmlRootElement
@XmlType(namespace = "http://example.com/bar")
public class Bar {
public Shared shared;
}

public class Shared {
public String string;
}

这些类中的每一个都分配给不同编译单元(模块)中的不同包。现在,当我在每个顶级类上使用 schemagen 时,我希望 Shared 类具有与顶级类相同的 namespace 。所以 Foo 的输出应该是这样的:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="foo" type="Foo"/>

<xs:complexType name="Foo">
<xs:sequence>
<xs:element name="shared" type="Shared" minOccurs="0"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="Shared">
<xs:sequence>
<xs:element name="string" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:schema>

然而,它不是这样工作的。相反,Shared 类具有默认命名空间,因此我得到了两个架构文件,一个用于 Foo 的命名空间,一个用于 Shared 的命名空间。

有没有明显的解决方案来解决此问题,即复制 Shared 类,从而不再共享它?

最佳答案

如果共享类应该与顶级类具有相同的 namespace ,则必须复制它。如果你真的想共享它,它必须在第三个 XSD 中定义并导入到两个顶级 XSD 中。所以 Foo 的结果应该看起来像:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://www.example.org/schema/foo"
xmlns:shared="http://www.example.org/schema/shared"
targetNamespace="http://www.example.org/schema/foo">

<xs:import namespace="http://www.example.org/schema/shared" schemaLocation="http://www.example.org/schema/shared/shared.xsd"/>

<xs:element name="foo" type="Foo"/>

<xs:complexType name="Foo">
<xs:sequence>
<xs:element name="shared" type="shared:Shared" minOccurs="0"/>
</xs:sequence>
</xs:complexType>

</xs:schema>

Shared 的 XSD 然后可以导入到两个顶级 XSD 中。如果您的共享 XSD 位于单独的项目中,您可能需要一个目录文件来指定其位置:

PUBLIC "http://www.example.org/schema/shared" "../../../../shared/src/main/xsd/shared.xsd"

我总是使用契约优先,即创建 XSD 并让 JAXB 生成类。您正在使用 schemagen 生成基于类的 XSD。以防万一您使用的是 jaxb2-maven-plugin 我发现了 Parameter transformSchemas这听起来像是在做你需要的。它允许您指定架构映射并将 xs:import 语句写入生成的 XSD。我没有尝试过,但希望对您有所帮助。

关于java - schemagen:如何共享类,而不是它们的命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18943003/

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