Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the default root element namespace prefix from XML generated using JAXB

I am using JAXB with spring-mvc framework to generate XML. This is the example of root element:

<ns2:urlset xmlns:ns2="http://www.example.com">

However, this is what I want (no XML namespace prefix ns2):

<urlset xmlns="http://www.example.com">

I've tried to use the following package-info.java to remove the default prefix ns2.

@javax.xml.bind.annotation.XmlSchema(  
    namespace = "http://www.example.com",   
    xmlns = {@javax.xml.bind.annotation.XmlNs(namespaceURI = "http://www.example.com", prefix="")},  
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.UNQUALIFIED)  
package com.example.code

The prefix can be changed to other value (than ns2) if I set prefix to another string. But the prefix can't be removed by setting prefix value to "". It still shows the default one ns2. Is there a way to remove the default prefix ns2?

Another question is that if the standalone attribute in the header of the XML can be removed too? If so, can it be done through package-info.java?

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
like image 625
Jin Huang Avatar asked Oct 21 '12 02:10

Jin Huang


2 Answers

Try this:

package-info.java

    @XmlSchema(
    namespace="http://www.sitemaps.org/schemas/sitemap/0.9", 
    elementFormDefault=XmlNsForm.QUALIFIED)
package com.example.model;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.XmlNsForm;

XmlUrlSet.java

@XmlAccessorType(value = XmlAccessType.NONE)
@XmlRootElement(name = "urlset", namespace = "http://www.sitemaps.org/schemas/sitemap/0.9")
public class XmlUrlSet {...}
like image 178
alex Avatar answered Sep 17 '22 18:09

alex


If @alex's answer did not work, you may have found a bug (at least, I think, that it is one) in the reference implementation of JAXB. I just had the same problem - if I added a JaxbElement to my model-class, the JAXB RI started ignoring my default namespace. I could not find another solution than switching to Eclipse MOXy (without any other modification) and it worked. (Caution: watch out for another bug in moxy)

Also for your second question, use this:

JAXBContext jc = JAXBContext.newInstance(...);
Marshaller m = jc.createMarshaler();
m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
like image 40
wrm Avatar answered Sep 20 '22 18:09

wrm