Java : Handling XML Documents

Created 19 June 2002 00:00
To retrieve values from an XML document, you need to import the following:
  import javax.xml.parsers.*;
  import org.w3c.dom.*;
  import javax.swing.*;
The text within elements is itself seen as a node, so to retrieve values from an XML document:
  Document doc = null;
  try {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance()
    doc = builder.parse(new FileInputStream(file));
  catch (Exception e) {
    throw new Exception(e.getMessage());
  NodeList nodeList = doc.getElementsByTagName("tagname");
  for (int i=0; i<nodeList.getLength(); i++) {
    Node node = nodeList.item(i);    NodeList list = node.getChildNodes();

To save values to an xml document, you also need to import:

  import javax.xml.transform.*;
  import javax.xml.transform.dom.*;

Save the document using a Transformer object:

  try {
    Transformer transformer = TransformerFactory.newInstance()
    DOMSource source = new DOMSource(yourDocument);
    StreamResult result = new StreamResult(yourFile);
    transformer.transform(source, result);
  catch (Exception e) {