Search code examples
javaxmljaxbprefix

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.

@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

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

This results in the following XML after marshalling

<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

<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.


Solution

  • First, you are creating the Foo element in the wrong namespace. Looking at your desired output, you also want the Foo element to be in the http://Foo/bar namespace. To fix this problem, specify that namespace URI when you create the QName, instead of passing an empty string as the first argument:

    // 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. You probably have a package-info.java file with an @XmlSchema annotation. 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.