使用没有ns2前缀的JDK的JAXB

c4k*_*c4k 12 jaxb xml-namespaces

在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;
Run Code Online (Sandbox Code Playgroud)

解决方案2:NamespacePrefixMapper

我创建了以下类并将映射器设置为marshaller:

// 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());
}
Run Code Online (Sandbox Code Playgroud)

使用com.sun.xml.bind.namespacePrefixMapper没有任何反应,使用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>
Run Code Online (Sandbox Code Playgroud)

你能帮帮我吗?

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

Xst*_*ian 1

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

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

NamespacePrefixMapper 在 JAVADOC 中说

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"
Run Code Online (Sandbox Code Playgroud)

否则如果使用包信息

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 "".
Run Code Online (Sandbox Code Playgroud)

我希望我已经为您提供了有关您问题的所有答案。