简体   繁体   English

在没有@XmlRootElement批注的情况下,JaxB编组元素时删除ns2前缀

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

I have an object that I want to marshall but the schema does not have the @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;
}

I marshalled the object by specifying a JaxBElement while marshalling 我通过在编组时指定JaxBElement来编组对象

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

This results in the following XML after marshalling 这在编组后产生以下XML

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

For my usecase I would like to marhsall this object without the ns2 prefix so that the XML would look like 对于我的用例,我想在不使用ns2前缀的情况下使用此对象,以便XML看起来像

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

How can I marshall this object without the prefix? 如何在没有前缀的情况下编组此对象?

Thanks in Advance. 提前致谢。

First, you are creating the Foo element in the wrong namespace. 首先,您在错误的命名空间中创建Foo元素。 Looking at your desired output, you also want the Foo element to be in the http://Foo/bar namespace. 查看所需的输出,您还希望Foo元素位于http://Foo/bar命名空间中。 To fix this problem, specify that namespace URI when you create the QName , instead of passing an empty string as the first argument: 要解决此问题,请在创建QName时指定该命名空间URI,而不是将空字符串作为第一个参数传递:

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

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

To get rid of the generated ns2 prefix for the namespace, you need to set the namespace prefix to an empty string. 要删除生成的名称空间的ns2前缀,需要将名称空间前缀设置为空字符串。 You probably have a package-info.java file with an @XmlSchema annotation. 您可能有一个带有@XmlSchema注释的package-info.java文件。 It should look like this: 它应该如下所示:

@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;

Note: Setting prefix = "" will cause JAXB to generate an xmlns attribute without a generated prefix name such as ns2 in your XML. 注意:设置prefix = ""将导致JAXB生成xmlns属性,而不会在XML中生成诸如ns2类的生成前缀名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM