我有大量的 java 对象列表,想使用 JAXB 编码没有根元素的列表。有可能吗?
我有一个类似这样的列表
List<Element> elements = new ArrayList<Element>
Expected Output:
<element>
----------
---------
</element>
<element>
---------
---------
<element>
我怎样才能以这种方式编码,
任何引用或提示将不胜感激。
最佳答案
您可以遍历列表,单独编码每个项目。您需要在 Marshaller
上设置 JAXB_FRAGMENT
属性,以防止 XML header 被写出。对于此用例,您只需创建一次 JAXBContext
和 Marshaller
。
import java.io.FileOutputStream;
import java.util.*;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Element.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
List<Element> elements = new ArrayList<>();
elements.add(new Element());
elements.add(new Element());
try(FileOutputStream fos = new FileOutputStream("src/forum18509018/out.txt")) {
for(Element element : elements) {
marshaller.marshal(element, fos);
}
}
}
}
关于java - 如何使用 JAXB 编码没有 XML 根元素的 java 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18509018/