Jaxb 生成的 xml - 根元素前缀问题 [英] Jaxb generated xml - problem with root element prefix

查看:30
本文介绍了Jaxb 生成的 xml - 根元素前缀问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 jaxb 生成 xml.我创建了 xsd 并生成了 java 类.但是当我生成 xml 时,我在根标记前加上前缀 ns2,这是我不想要的.

I am trying to generate xml using jaxb. I created xsd and generated java classes. But when I generate xml, I am geeting prefix ns2 to the root tag, which I don't want.

例如:我希望根标记为

ex: I want root tag to be

 <report>
   <id>rep 1</id>
</report>

, 但得到

, But getting as

<ns2:report>
....
</ns2:report>

在生成的java类中,我给注释为@XmlRootElement(name="report",namespace="urn:report")

In the generated java class, I gave annotation as @XmlRootElement(name="report",namespace="urn:report")

有人可以帮忙吗

推荐答案

如果这是你的班级:

package example;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="report",namespace="urn:report")
public class Root {

    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}

那么在根元素上有一个前缀是有道理的,因为您已经指定root"元素是命名空间限定的,而id"元素不是.

Then it makes sense that there is a prefix on the root element, because you have specified that the "root" element is namespace qualified and the "id" element is not.

<ns2:report xmlns:ns2="urn:report">
    <id>123</id>
</ns2:report>

如果您向模型中添加了 package-info 类,则可以利用 @XmlSchema 注释:

If you add a package-info class to your model, you can leverate the @XmlSchema annotation:

@XmlSchema(
        namespace = "urn:report",
        elementFormDefault = XmlNsForm.QUALIFIED)
package example;

import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

然后 JAXB 实现可能会选择利用默认命名空间,但请注意,现在所有元素都是命名空间限定的,可能与您的 XML 模式匹配,也可能不匹配:

Then the JAXB implementation may choose to leverage the default namespace, but note now all of the elements are namespace qualified which may or may not match your XML schema:

<report xmlns="urn:report">
    <id>123</id>
</report>

有关 JAXB 和命名空间的更多信息,请参阅:

For more information on JAXB and namespaces see:

这篇关于Jaxb 生成的 xml - 根元素前缀问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆