Peter Peter - 5 months ago 29
Java Question

How to append xml file in java

I've been using xml files to save data from my java program. I'm using the java DOM api. I want to add to the document by adding an element and then adding children to that element.
I tried doing it using this code but when i run it it does nothing. Is there another way of doing it that would be simple and work better? is there a way i can get this code working?

File file = new File("C:/users/peter/desktop/newxml.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);
Element newB = document.createElement("B");
Element newC = document.createElement("c");
Element newD = document.createElement("d");
Element newE = document.createElement("e");


you should check out the JAXB API. If I understand right, you're xml looks like this:


So code would be:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;

public class B {
    @XmlElement public String C; // sloppy, probably should be type Integer or something
    @XmlElement public String D;
    @XmlElement public String E;

// then, somewhere else in your code you want to serialize...
B b = new B();
b.C = "11";
b.D = "21";
b.E = "31";

JAXBContext c = JAXBContext.newInstance(B.class);

// where w is a Writer instance
c.createMarshaller().marshal(b, w);