[英]How to marshal a java List with out XML root element using JAXB?
I have huge list of java Objects, want to marshal that list without a root element, using JAXB. 我有庞大的java对象列表,希望使用JAXB编组没有根元素的列表。 Is it possible to do ?.
有可能吗?
I have a list something like this 我有一个这样的清单
List<Element> elements = new ArrayList<Element>
Expected Output:
<element>
----------
---------
</element>
<element>
---------
---------
<element>
How can I marshal in such a way, 我怎么能以这种方式编组,
Any reference or hint will be greatly appreciated. 任何参考或提示将不胜感激。
You could iterate over the list marshalling each item individually. 您可以遍历列表单独编组每个项目。 You will need to set the
JAXB_FRAGMENT
property on the Marshaller
to prevent the XML header from being written out. 您需要在
Marshaller
上设置JAXB_FRAGMENT
属性,以防止写出XML标头。 You will only need to create the JAXBContext
and Marshaller
once for this use case. 您只需要为此用例创建一次
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);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.