我目前的编组结果是这份文件:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rootElem version="1">
<list>
<entry>
<key xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">someValue</key>
<value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">42</value>
</entry>
<entry>
<key xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">otherValue</key>
<value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">24</value>
</entry>
</list>
</rootElem>
我希望marshaller提取NS,因此它不会在每个元素上重复,如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<rootElem version="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<list>
<entry>
<key xsi:type="xs:string">someValue</key>
<value xsi:type="xs:string">42</value>
</entry>
<entry>
<key xsi:type="xs:string">otherValue</key>
<value xsi:type="xs:string">24</value>
</entry>
</list>
</rootElem>
如何做到这一点?
我已经找到了an answer这个问题,但它并没有完全解决问题(它只是将实例移动到rootElem)。
这就是我编辑它的方式:
JAXBContext jc = JAXBContext.newInstance(RootElem.class);
Marshaller m = jc.createMarshaller();
m.setProperty("jaxb.formatted.output", true);
m.marshal(rootElem, file);