aanoop
aanoop

Reputation: 31

JAXB generate XML element with package name

I am trying to generate a simple XML from POJO using JAXB. Here is my XML output:

<Customer>
    <name>abcd</name>
</Customer>
For this POJO:

@XmlRootElement
private static class Customer {
    @Max(5)
    private String name;
    public String getName() {
        return name;
    }
    @XmlElement
    public void setName(String name) {
        this.name = name;
    }
}

I want to have XML root element completely description ie with entire package name. So XML output should be:

<com.some.pkg.Customer>
    <name>abcd1231</name>
</com.some.pkg.Customer>

Here is my Java code:

Customer s = new Customer();
    s.setName("abcd");

    JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    StringWriter sw = new StringWriter();
    jaxbMarshaller.marshal(s, sw);
    System.out.println(sw.toString());

Is this doable with JAXB? Which property I have to set to get that kind of output ?

Upvotes: 1

Views: 1275

Answers (1)

user268396
user268396

Reputation: 11996

<com.some.pkg.Customer>
    <name>abcd1231</name>
</com.some.pkg.Customer>

This is invalid XML: element names cannot contain dots or spaces, or other punctuation... though - is allowed. So this specific XML cannot be generated, with JAXB or otherwise (as it's not XML).

Instead, the JAXB thing to do is to use annotations on a package-info file which customise how namespacing of the element is handled (namespace prefixes, generating fully qualified names etc.).

That way you would end up with something like:

<ns:Customer xmlns:ns="com.some.pkg">
  <ns:name>abcd1231</ns:name>
</ns:Customer>

Example package-info.java file for com.some.pkg

@XmlSchema(namespace = "com.some.pkg", 
           xmlns = { @XmlNs(namespaceURI = "com.some.pkg", prefix = "ns") },
           attributeFormDefault = XmlNsForm.QUALIFIED, 
           elementFormDefault = XmlNsForm.QUALIFIED)
package com.some.pkg;

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

Upvotes: 2

Related Questions