Apache XMLBeans – output XML without a namespace
January 21, 2009 8 Comments
This is again something that I need to know how to do but never remember how when time it tight.
Apache XMLBeans http://xmlbeans.apache.org/ is a great tool for working with XML in Java, but it requires the XML Schema being used to create the objects from XML to have a Namespace. The namespace ends up being part of the package structure for the Objects created and I guess having a unique path for these is a good idea. However, this requirement can be a bit of a pain, when working with some simple XML structures that do not have a namespace. Especially when your ready to persist the XML Bean objects to XML source. If a namespace is added to your XML Schema that the XML Bean objects are created from, XML source generated from them will by default also have the namespace. I can never remember how to output the XML source without a namespace and so I am writing it down here where I can get at it with a click, and maybe this will help someone else as well.
There are two key steps to remove the Namespace when outputting XML Source.
- Tell it to use the default namespace:
- Tell it that you have already declared the default namespace:
dnsMap.put("", "http://example.com/schemas/DefaultNnameSpace"); xmlops.setSaveImplicitNamespaces(dnsMap);
After this, you can output as normal:
xmlops.setSavePrettyPrint(); xmlops.setSaveNamespacesFirst(); retString = myXMLDoc.xmlText(xmlops); return retString;
Note: the research and testing to solve this was done using XMLBeans v2.4.0