Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to marshal without a namespace?

Tags:

I have a fairly large repetitive XML to create using JAXB. Storing the whole object in the memory then do the marshaling takes too much memory. Essentially, my XML looks like this:

<Store>   <item />   <item />   <item /> ..... </Store> 

Currently my solution to the problem is to "hard code" the root tag to an output stream, and marshal each of the repetitive element one by one:

aOutputStream.write("<?xml version="1.0"?>") aOutputStream.write("<Store>")  foreach items as item   aMarshaller.marshall(item, aOutputStream) end aOutputStream.write("</Store>") aOutputStream.close() 

Somehow the JAXB generate the XML like this

 <Store  xmlns="http://stackoverflow.com">   <item xmlns="http://stackoverflow.com"/>   <item xmlns="http://stackoverflow.com"/>   <item xmlns="http://stackoverflow.com"/> ..... </Store> 

Although this is a valid XML, but it just looks ugly, so I'm wondering is there any way to tell the marshaller not to put namespace for the item elements? Or is there better way to use JAXB to serialize to XML chunk by chunk?

like image 256
Alvin Avatar asked May 12 '10 05:05

Alvin


People also ask

How do you Unmarshal XML without namespace?

Unmarshaller. unmarshal(rootNode, MyType. class); you don't need to have a namespace declaration in the XML, since you pass in the JAXBElement that has the namespace already set.

How do I remove namespace prefix Jaxb?

You can use the NamespacePrefixMapper extension to control the namespace prefixes for your use case. The same extension is supported by both the JAXB reference implementation and EclipseLink JAXB (MOXy).


2 Answers

The following did the trick for me:

         XMLStreamWriter writer = ...          writer.setNamespaceContext(new NamespaceContext() {             public Iterator getPrefixes(String namespaceURI) {                 return null;             }              public String getPrefix(String namespaceURI) {                 return "";             }              public String getNamespaceURI(String prefix) {                 return null;             }         }); 
like image 185
Tamas Kornai Avatar answered Sep 28 '22 12:09

Tamas Kornai


Check your package-info.java (in the package where your jaxb-annotated classes are). There is the namespace attribute of @XmlSchema there.

Also, there is a namespace attribute in the @XmlRootElement annotation.

like image 39
Bozho Avatar answered Sep 28 '22 12:09

Bozho