I have huge list of java Objects, want to marshal that list without a root element, using JAXB. Is it possible to do ?.
我有大量的java对象列表,希望使用JAXB在没有根元素的情况下编组该列表。有可能吗?
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.
如有任何参考或提示,将不胜感激。
1 个解决方案
#1
4
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. You will only need to create the JAXBContext
and Marshaller
once for this use case.
您可以对列表进行迭代,分别对每个项进行编组。您需要在编组器上设置JAXB_FRAGMENT属性,以防止写入XML头。您只需要为这个用例创建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);
}
}
}
}
#1
4
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. You will only need to create the JAXBContext
and Marshaller
once for this use case.
您可以对列表进行迭代,分别对每个项进行编组。您需要在编组器上设置JAXB_FRAGMENT属性,以防止写入XML头。您只需要为这个用例创建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);
}
}
}
}