Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jaxb generated xml - problem with root element prefix

Tags:

java

xml

jaxb

I am trying to generate xml using jaxb. I created xsd and generated java classes. But when I generate xml, I am geeting prefix ns2 to the root tag, which I don't want.

ex: I want root tag to be

 <report>
   <id>rep 1</id>
</report>

, But getting as

<ns2:report>
....
</ns2:report>

In the generated java class, I gave annotation as @XmlRootElement(name="report",namespace="urn:report")

Can some one pls help

like image 581
crazyTechie Avatar asked Nov 30 '10 10:11

crazyTechie


2 Answers

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

}

Then it makes sense that there is 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 your model, you can leverate 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 may choose to leverage the default namespace, but note now all of the elements are namespace qualified which may or may not match your XML schema:

<report xmlns="urn:report">
    <id>123</id>
</report>

For more information on JAXB and namespaces see:

  • http://bdoughan.blogspot.com/2010/08/jaxb-namespaces.html
like image 104
bdoughan Avatar answered Nov 04 '22 21:11

bdoughan


Take a look at this answer. It describes how to use a SAX Filter to remove any namespace.

like image 31
dogbane Avatar answered Nov 04 '22 21:11

dogbane