JAXB: How do I annotate classes so that they belong to different namespaces?

21,269
@XmlRootElement(name="someRootElement", namespace = "urn:my:ns1")
class Test {
    @XmlElement(name="someElement", namespace="urn:my:ns1")
    String elem1 = "One";

    @XmlElement(name="someElement", namespace="urn:my:ns2")
    String elem2 = "Two";

    @XmlElement(name="someElement", namespace="urn:my:ns3")
    String elem3 = "Three";
}

This marshals into the following XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<someRootElement xmlns="urn:my:ns1" xmlns:ns2="urn:my:ns2" xmlns:ns3="urn:my:ns3">
    <someElement>One</someElement>
    <ns2:someElement>Two</ns2:someElement>
    <ns3:someElement>Three</ns3:someElement>
</someRootElement>

If you are using JAXB RI and don't like the default ns2 and ns3 namespace prefixes, you need to provide your own NamespacePrefixMapper.

Share:
21,269
ivan_ivanovich_ivanoff
Author by

ivan_ivanovich_ivanoff

!!! Netbeans 6.7 RELEASED !!! C is far better and easier than Java! Why? It is easier to use void pointers and to do pointer arithmetic, than explaining the basic concepts of OOP to a C programmer. Joke of the century: PHP is good, because it works... "PHP programming" is an oxymoron. There is no PHP programming. There is only PHP scriptkidding. There are two types of people who use PHP: - those who don't know other languages, - and those who HAVE TO use it Java is to JavaScript what Car is to Carpet. The LHC is the wrong answer to the technological singularity.

Updated on July 16, 2022

Comments

  • ivan_ivanovich_ivanoff
    ivan_ivanovich_ivanoff almost 2 years

    I want to have JAXB-annotated classes which would be marshalled/unmarshalled to different XML namespaces.

    What I need is something like:

    <someRootElement xmlns="urn:my:ns1"
        xmlns:a="urn:my:ns2" xmlns:b="urn:my:ns3">
    
      <someElement/>
      <a:someElement/>
      <b:someElement/>
    
    </someRootElement>
    

    How can it be done?

    Can it be done programatically? (without the need for JAXB's .xjb bindings file?)