How to have custom namespace prefix

jaxb

Solution

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

- http://blog.bdoughan.com/2011/11/jaxb-and-namespace-prefixes.html

Problem

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"?

Original source