使用没有ns2前缀的JDK的JAXB

时间:2013-01-30 10:34:47

标签: 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;

解决方案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());
}

使用 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>

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

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

2 个答案:

答案 0 :(得分:1)

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

我过去遇到过同样的问题,我为每个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"

否则,如果使用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 "".

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

答案 1 :(得分:0)

我今天遇到了同样的问题。生产机器有Java 6,当我部署我的应用程序时,我得到了ns2前缀。这就是我解决它的方式。生产服务器只有Java 1.6补丁21

  1. 我确保在我的包中有一个package-info.java文件,其中所有类都是使用Jaxb生成的。我查了一下,@ XmlSchema都是自动生成的,所以我没有弄乱任何一个。不要使用namespacemapper,这只会让我感到困惑。

  2. 在我的pom.xml文件中,我添加了jaxb-impl依赖项:   com.sun.xml.bind   JAXB的IMPL   2.2.5-B04

    并指定源和目标为1.6。一个maven干净的安装和包装并部署到生产中,一切看起来都不错。 下一步是确保生产机器升级到Java 7.希望这有助于:)