I am new to JAXB. I am able to populate the XML. In my case I need my namespace prefix as
<set xmlns="www.google.com"
xmlns:myName="www.google.com">
instead of
<set xmlns="www.google.com"
xmlns:ns2="www.google.com">
I have used package-info
class and also the @XmlType
annotation. Do I need to add any variable to get the desired name for the second namespace like "xmlns:MyName' instead of "xmlns:ns2"?
If you are using EclipseLink JAXB (MOXy) as your JAXB provider or a recent version of the JAXB RI then you can do the following:
package-info
You can use the @XmlNs
annotation on the xmlns
property of the @XmlSchema
annotation to specify the prefix for a namespace.
@XmlSchema(
namespace="www.google.com",
elementFormDefault = XmlNsForm.QUALIFIED,
xmlns={
@XmlNs(namespaceURI = "www.google.com", prefix = ""),
@XmlNs(namespaceURI = "www.google.com", prefix = "myName"),
})
package forum13817126;
import javax.xml.bind.annotation.*;
Java Model
Below is a simple Java model that I will use for this example.
package forum13817126;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Set {
}
Demo Code
The following demo code will create an instance of the domain model and marshal it to XML.
package forum13817126;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Set.class);
Set set = new Set();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(set, System.out);
}
}
Output
Below is the output from running the demo code.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<myName:set xmlns="www.google.com" xmlns:myName="www.google.com"/>
For More Information
You need to add an xmlns
property on the @XmlSchema
annotation in package-info
. Its value is an array of annotations giving suggested prefix mappings for the marshaller. While it is technically allowed to ignore these suggestions I find they are usually respected as long as there are no clashes (two different packages suggesting the same prefix for different URIs).
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