Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have custom namespace prefix

Tags:

jaxb

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

like image 571
user1894202 Avatar asked Oct 05 '22 17:10

user1894202


2 Answers

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
like image 88
bdoughan Avatar answered Oct 10 '22 04:10

bdoughan


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).

like image 33
Ian Roberts Avatar answered Oct 10 '22 02:10

Ian Roberts