Java – JAXB generated XML – root element prefix problem
I'm trying to generate XML using JAXB I created XSD and generated Java classes
For example: I want a root tag
<report> <id>rep 1</id> </report>
, but get
<ns2:report> .... </ns2:report>
In the generated Java class, I annotated @ xmlrootelement (name = "report", namespace = "urn: report")
Some people can help
Solution
If this is your class:
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; } }
It makes sense to have 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>
If you add a package info class to the model, you can use the @ XMLSchema annotation:
@XmlSchema( namespace = "urn:report",elementFormDefault = XmlNsForm.QUALIFIED) package example; import javax.xml.bind.annotation.XmlNsForm; import javax.xml.bind.annotation.XmlSchema;
Then, the JAXB implementation can choose to use the default namespace, but now note that all elements are namespace qualified, and they may or may not match your XML Schema:
<report xmlns="urn:report"> <id>123</id> </report>
For more information about JAXB and namespaces, see:
> http://bdoughan.blogspot.com/2010/08/jaxb-namespaces.html