java 如何使用 JAXB 设置默认命名空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17478317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:07:04  来源:igfitidea点击:

How to set the default namespace using JAXB

javaserializationjaxbatom-feed

提问by user86834

I have a ATOM-XML representation of my data that is returned via a Spring MVC web service. I'm using JAXB to do the serialization, I have a number of namespaces but I want the default namespace set to Atom with no prefix. Here is what I have so far in package-info.javabut the atom prefix is being set to ns3.

我有一个通过 Spring MVC Web 服务返回的数据的 ATOM-XML 表示。我正在使用 JAXB 进行序列化,我有许多命名空间,但我希望将默认命名空间设置为没有前缀的 Atom。这是我到目前为止的内容,package-info.java但原子前缀被设置为 ns3。

@XmlSchema(namespace = com.mycomponay.foo.ATOM_NAMESPACE,
xmlns = { 
    @XmlNs(prefix = "foo", namespaceURI = com.mycomponay.foo.NAMESPACE_FOO),
}, elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.mycompany.web;

import javax.xml.bind.annotation.XmlNs;

Also I noticed the namespaces display in chrome but not in Firefox.

我还注意到命名空间显示在 chrome 中,但不在 Firefox 中。

回答by bdoughan

Try adding an @XmlNsannotation with prefix ""for the namespace you want to appear as the default.

尝试为要显示为默认名称的命名空间添加@XmlNs带有前缀的注释""

@XmlSchema(
    namespace = com.mycompany.foo.ATOM_NAMESPACE,
    xmlns = { 
        @XmlNs(prefix = "", namespaceURI = com.mycompany.foo.ATOM_NAMESPACE),
        @XmlNs(prefix = "foo", namespaceURI = com.mycompany.foo.NAMESPACE_FOO)
    }, 
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.mycompany.web;

import javax.xml.bind.annotation.*;

Note:

笔记:

The namespaces specified in the @XmlSchemaannotation are meant to affect the generation of the XML Schema and are not guaranteed to be used when a object model is marshalled to XML. However EclipseLink JAXB (MOXy)and recent versions of the JAXB reference implementationwill use them whenever possible.

@XmlSchema注解中指定的命名空间旨在影响 XML Schema 的生成,并且不能保证在将对象模型编组为 XML 时使用。但是EclipseLink JAXB (MOXy)和最新版本的JAXB 参考实现将尽可能使用它们。

For More Information

想要查询更多的信息

回答by lwpro2

if you are using separate class for XML element, annotate it with namespace="", would work.

如果您为 XML 元素使用单独的类,用 namespace="" 注释它,会起作用。