users@jaxb.java.net

Re: remove namespace prefix from child elements by setting default namespace locally?

From: Wolfgang Laun <wolfgang.laun_at_gmail.com>
Date: Thu, 24 Mar 2011 09:55:33 +0100

Prefixes are just shorthands for the lengthy namespace URIs.

Primarily, you'll have to put Aroot into namespace
http://www.w3.org/2005/Aand Broot into namespace
http://www.w3.org/2005/B <http://www.w3.org/2005/A>. The namespace is
derived from the package, or set by customization; or you define it directly
in an annotation (if you don't use xjc and generated Java sources).

-W


On 23 March 2011 23:20, ginger <ggtech888_at_gmail.com> wrote:

> Hello, JAXB Gurus,
>
> We are using RESTEasy to implement RESTful APIs, which employs JAXB for its
> marshal/unmarshal job. What we have found very inconvenient is the fact that
> we can only define default namespace once for the whole document marshalled,
> rather than defining it locally for every root element that we have a
> namespace URI.
>
> Eg, what we want is like the following
>
> <Aroot xmlns="http://www.w3.org/2005/A">
> <Achild....>
> <Broot xmlns="http://www.w3.org/2005/B">
> <Bchild....>
> ...
> </Bchild>
> </Achild>
> </Aroot>
>
> so there are 2 levels of default namespace, when it is within A's child
> elements, the default namespace is A; and when it steps into B's child
> element, it is B
>
> But JAXB (2.1.9) gives sth like
>
> <ANS:Aroot xmlns:ANS="http://www.w3.org/2005/A">
> <ANS:Achild....>
> <Broot>
> <Bchild....>
> ...
> </Bchild>
> </ANS:Achild>
> </ANS:Aroot>
>
> therefore only B's namespace is recognized as the default and used from
> start to end. We do extend NamespacePrefixMapper and set it in the
> marshaller used as following:
>
> NamespacePrefixMapper mapper = new NamespacePrefixMapper()
> {
> public String getPreferredPrefix(String namespace, String s1, boolean b)
> {
> if (namespace.equals("http://www.w3.org/2005/A")) return "ANS";
> else return s1;
> }
> };
>
> marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", mapper);
>
> If we replace
> return "ANS"
> with
> return "";
>
> then A's child elements are preceeded with ns1, as people have commented
> online. Is it do-able with JAXB 2.19 to achieve what we want?
>
> Thanks a million for your kind helps in advance
>
> gigi
>