gpt4 book ai didi

jaxb - 使用没有 ns2 前缀的 JDK 的 JAXB

转载 作者:行者123 更新时间:2023-12-04 01:14:41 51 4
gpt4 key购买 nike

在阅读了 Oracle 论坛、Stackoverflow、java.net 上所有关于此的帖子后,我终于在这里发帖了。
我正在使用 JAXB 创建 XML 文件,但问题是它添加了著名的 ns2 在我的元素之前添加前缀,我已经尝试了所有没有人为我工作的解决方案。
java -version 给出“1.6.0_37”

解决方案 1:使用 package-info.java

我在包含我的 @Xml* 注释类的包中创建了具有以下内容的文件:

@XmlSchema(
namespace = "http://mynamespace",
elementFormDefault = XmlNsForm.QUALIFIED,
xmlns = {
@XmlNs(namespaceURI = "http://mynamespace", prefix = "")
}
)
package com.mypackage;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

解决方案 2:NamespacePrefixMapper

我创建了以下类并将映射器设置为编码器:
// Change mapper to avoid ns2 prefix on generated XML
class PreferredMapper extends NamespacePrefixMapper {
@Override
public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
return "";
}
}
NamespacePrefixMapper mapper = new PreferredMapper();
try {
marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", mapper);
}
catch (PropertyException e) {
logger.info("No property for com.sun.xml.bind.namespacePrefixMapper found : " + e.getMessage());
}

使用 com.sun.xml.bind.namespacePrefixMapper 没有任何 react ,使用 com.sun.xml.internal.bind.namespacePrefixMapper,它会抛出异常。

我还在我的 pom 中添加了 maven 依赖项,但似乎 JRE 版本具有更高的优先级:
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.4</version>
</dependency>

你能帮我解决这个问题吗?

PS:由于构建原因,我不能在我的类路径中直接包含 jar。
PS2:我不能使用JDK7。
提前致谢。

最佳答案

没有 MOXy 的实现是不可能的。 JAXB 如果首选前缀是“”,它会生成一个新前缀。

我过去也遇到过同样的问题,我为每个 package-info.java 配置了每个前缀。

NamespacePrefixMapper 在 Java 中说

null if there's no prefered prefix for the namespace URI.
In this case, the system will generate a prefix for you.

Otherwise the system will try to use the returned prefix,
but generally there's no guarantee if the prefix will be
actually used or not.

return "" to map this namespace URI to the default namespace.
Again, there's no guarantee that this preference will be
honored.

If this method returns "" when requirePrefix=true, the return
value will be ignored and the system will generate one"

否则如果使用 package-info
we know we can't bind to "", but we don't have any possible name at hand.
generate it here to avoid this namespace to be bound to "".

我希望我已经给了你所有关于你的问题的答案。

关于jaxb - 使用没有 ns2 前缀的 JDK 的 JAXB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14601877/

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