在 JaxB 编组没有 @XmlRootElement 注释的元素时删除 ns2 前缀

Remove ns2 prefix while JaxB marshalling an Element without @XmlRootElement annotation

我有一个要编组的对象,但架构没有 @XmlRootElement 注释。

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
public static class Foo
{
    @XmlAttribute(name = "test1")
    public final static String TEST_1 = "Foo";

    @XmlElement(name = "Element1", required = true)
    protected String element1;

    @XmlElement(name = "Element2", required = true)
    protected String element2;
}

我在编组时通过指定 JaxBElement 编组了对象

QName qName = new QName("", "Foo");
jaxb2Marshaller.marshal(new JAXBElement(qName, Foo.class, fooObj), new StreamResult(baos));

编组后 XML 结果如下

<Foo xmlns:ns2="http://Foo/bar" test1="Foo">
    <ns2:Element1>000000013</ns2:Element1>
    <ns2:Element2>12345678900874357</ns2:Element2>
</Foo>

对于我的用例,我想在没有 ns2 前缀的情况下编组这个对象,以便 XML 看起来像

<Foo xmlns="http://Foo/bar" test1="Foo">
    <Element1>000000013</Element1>
    <Element2>12345678900874357</Element2>
</Foo>

如何在没有前缀的情况下编组此对象?

提前致谢。

首先,您在错误的命名空间中创建了 Foo 元素。查看所需的输出,您还希望 Foo 元素位于 http://Foo/bar 命名空间中。要解决此问题,请在创建 QName 时指定命名空间 URI,而不是将空字符串作为第一个参数传递:

// Wrong
QName qName = new QName("", "Foo");

// Right
QName qName = new QName("http://Foo/bar", "Foo");

要删除为命名空间生成的 ns2 前缀,您需要将命名空间前缀设置为空字符串。您可能有一个带有 @XmlSchema 注释的 package-info.java 文件。它应该是这样的:

@XmlSchema(namespace = "http://Foo/bar",
           elementFormDefault = XmlNsForm.QUALIFIED,
           xmlns = @XmlNs(prefix = "", namespaceURI = "http://Foo/bar"))
package com.mycompany.mypackage;

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

注意:设置 prefix = "" 将导致 JAXB 生成 xmlns 属性,而没有生成的前缀名称,例如 XML.

中的 ns2