Showing posts with label XML Streaming. Show all posts
Showing posts with label XML Streaming. Show all posts

Wednesday, June 24, 2015

XML Streaming tip while using JAXB

Always streaming to xml files is recommended over full DOM writes.

If you are writing a big xml file and all child elements will not be written in one stretch or method call then writing individual fragments is efficient and practical.

Sample xml may look like:

<MyRoot>
   <Child id="1" type="a"/>
   <Child id="2" type="a"/>
   <Child id="3" type="a"/>
   .
   .
   .
   <Child id="1001" type="b"/>
   <Child id="1002" type="b"/>
   <Child id="1003" type="b"/>
   .
   .
   .
</MyRoot>

Lets us say <Child> elements of type "a" are to be added by method1() and type "b" are to be added by method2() then following snippet of code allows each method to independently write to same xml file in fragments. i.e without root element.

public void method1() {

 try {
                Employee emp1 = new Employee();
        emp1.setId(100);
        emp1.setFirstName("John");
        emp1.setLastName("Macy");
        emp1.setAge(29);

                Employee emp2 = new Employee();
        emp2.setId(88);
        emp2.setFirstName("Linda");
        emp2.setLastName("Stuard");
        emp2.setAge(25);

File file = new File("C:\\myFile.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
                //This property allows writing xml child nodes without root element

jaxbMarshaller.marshal(emp1, file);
                jaxbMarshaller.marshal(emp2, file);
 } catch (JAXBException e) {
e.printStackTrace();
 }

}

myFile.xml contents after execution of this piece of code looks as follows (without root element):

<Employee>
    <Id>100</Id>
    <FirstName>John</FirstName>
    <LastName>Macy</LastName>
    <Age>29</Age>
</Employee>
<Employee>
    <Id>88</Id>
    <FirstName>Linda</FirstName>
    <LastName>Stuard</LastName>
    <Age>25</Age>
</Employee>