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"?>
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 {...}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With