简体   繁体   中英

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. 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. You will only need to create the JAXBContext and Marshaller once for this use case.

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);
           }
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM