4

I've got an xml file looked like this. employees.xml

<Employees>
    <Employee>
        <FirstName>myFirstName</FirstName>
        <LastName>myLastName</LastName>
        <Salary>10000</Salary>
    <Employee>
</Employees>

Now how do I add new Employee elements to the existing XML file?.. An example code is highly appreciated.

Aruna Karunarathna
  • 981
  • 2
  • 23
  • 55
  • 2
    Read in the file, do the modifications in memory, write out the complete file a new. You have not fallen in the trap of using a flat file as a database? – Thorbjørn Ravn Andersen Jun 09 '12 at 15:50
  • 1
    @Thorbjørn Ravn Andersen - XML is not really a flat file format. – Don Roby Jun 09 '12 at 16:06
  • 1
    @DonRoby Really? What is it then (when as in this case it is stored in a file)? – Thorbjørn Ravn Andersen Jun 09 '12 at 16:09
  • 1
    @Thorbjørn Ravn Andersen - See http://en.wikipedia.org/wiki/Flat_file_database for flat file... XML is not this, but hierarchically structured data. Though it is generally stored in files, they're not flat. – Don Roby Jun 09 '12 at 16:18
  • 1
    @DonRoby please revisit the sample XML, and consider if e.g. `` could not be considered a suitable delimiter (with similar delimiters for the rest of the fields) and hence this particular XML dialect (as opposed to XML in general) _is_ a flat file. – Thorbjørn Ravn Andersen Jun 09 '12 at 16:30
  • http://thegreenoak.blogspot.com/2012/07/writing-string-value-to-xml-file-using.html – djangofan Jul 28 '12 at 00:06

5 Answers5

6

You can't 'write nodes to an existing XML file.' You can read an existing XML file into memory, add to the data model, and then write a new file. You can rename the old file and write the new file under the old name. But there is no commonly-used Java utility that will modify an XML file in place.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
2

Please use xstream to parse your file as an object, or create a list with employees and then you can directly convert that to xml.

Felix Christy
  • 2,179
  • 1
  • 19
  • 32
2

I think this link can be useful for you.

Here you have samples how to read / parse, modify (add elements) and save (write to xml file again).

The following samples you can find at: http://www.petefreitag.com/item/445.cfm

Read:

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("/path/to/file.xml");

Modify:

// attributes
Node earth = doc.getFirstChild();
NamedNodeMap earthAttributes = earth.getAttributes();
Attr galaxy = doc.createAttribute("galaxy");
galaxy.setValue("milky way");
earthAttributes.setNamedItem(galaxy);

// nodes
Node canada = doc.createElement("country");
canada.setTextContent("ca");
earth.appendChild(canada);

Write XML file:

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);

String xmlString = result.getWriter().toString();
System.out.println(xmlString);
Francisco Spaeth
  • 23,493
  • 7
  • 67
  • 106
2

To add to an existing XML file, you generally need to read it in to an internal data structure, add the needed data in the internal form and then write it all out again, overwriting the original file.

The internal structure can be DOM or one of your own making, and there are multiple ways of both reading it in and writing it out.

If the data is reasonably small, DOM is probably easiest, and there is some sample code in the answers to this related question.

If your data is large, DOM will not do. Possible approaches are to use SAX to read and write (though SAX is traditionally only a reading mechanism) as described in an answer to another related question.

You might also want to consider JAXB or (maybe even best) StAX.

Community
  • 1
  • 1
Don Roby
  • 40,677
  • 6
  • 91
  • 113
1

You need to use DOM to write/edit your xml file.
It's very easy:
You just need to create nodes and add attributes to it.
You can also write/edit XSLT files by using DOM.
just search google for DOM java

GingerHead
  • 8,130
  • 15
  • 59
  • 93
  • Thanks dude. Ye I tried Dom. But the problem I have faced is that I was not able to write new nodes to an existing xml file. – Aruna Karunarathna Jun 09 '12 at 15:43
  • 1
    on the contrary its very easy, you just need to parse it, then search the node you need to add new nodes to then add to it the needed nodes. – GingerHead Jun 09 '12 at 15:48