How to marshal without a namespace?

2020-01-28 03:46发布

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?

标签: java xml jaxb
7条回答
我命由我不由天
2楼-- · 2020-01-28 04:32

There is a very simple way to get rid of namespace prefixes in your case: just set the attribute elementFormDefault to unqualified in your schema, like this:

<xs:schema attributeFormDefault="unqualified" elementFormDefault="unqualified"
       xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns:your="http://www.stackoverflow.com/your/namespace">

You will get the namespace prefix only in the first tag:

<ns1:your xmlns:ns1="http://www.stackoverflow.com/your/namespace">

I hope this helps.

Regards Pawel Procaj

查看更多
登录 后发表回答