Element Traverse

public static void display(Element element, int depth) {
    // create a string of 'depth' tabs
    String indent = "";
    for (int i = 0; i < depth; i++)
        indent = indent.concat("\t");

    // get the name of the node
    String name = element.getNodeName();

    // display the beginning of the node
    System.out.printf("%sBEGIN(%s)\n", indent, name);

    NodeList nodes = element.getChildNodes();
    // for each node, display it (and children if any)
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);

        // is it a node containing child nodes?
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // it is, so display the child at depth + 1
            display((Element) node, depth + 1);

            // does the node contain text?
        } else if (node.getNodeType() == Node.TEXT_NODE) {
            // it does, so get the text and display it in quotes
            Text textNode = (Text) node;
            String data = textNode.getTextContent();
            // the string could contain spaces, new lines or tabs on either side of it, so trim these off
            data = data.trim();
            // anything left of the string? if so, display it
            if (data.length() > 0) System.out.printf("\t%s'%s'\n", indent, data);
        }
    }

    // display end of the node
    System.out.printf("%sEND(%s)\n", indent, name);
}

XPath

//1.	What degree is the student registered for?
path.evaluate("/academic_record/student/degree", doc)

//2.	How many years has the student studied?
path.evaluate("count(/academic_record/student/degree)", doc)

//3.	In 2002 what was the mark obtained for the June exams for WRA101?
path.evaluate("/academic_record/record/academic_year[@year=2002]/module[@code='WRA101']/@grade", doc)

//4.	How many exams were written for WRA101 (including supplementary exams)?
path.evaluate("count(/academic_record/record/academic_year/module[@code='WRA101' and @result!='No DP'])", doc)

//5.	How many supplementary exams (for different modules) did the student write?
path.evaluate("count(/academic_record/record/academic_year/module[@code='WRA101' and @result='Supplementary'])", doc)

//6.	In 2003, what is the module code of the 2nd module enrolled for?
path.evaluate("/academic_record/record/academic_year[@year=2003]/module[2]/@code", doc)

Create Existing XML for Querying

private static void CreateAndSaveXML() throws Exception {
    // create DocumentBuilder to parse XML document
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    // load document and parse to create tree
    File fin = new File("items.xml");
    Document doc = builder.parse(fin);

    // create xpath object that will allow document to be queried
    XPathFactory xpFactory = XPathFactory.newInstance();
    XPath path = xpFactory.newXPath();

    // query the document and save out nodes that match a specified criteria
    // create document
    Document outputDoc = createDoc();
    // create root element and attach to document
    Element results = outputDoc.createElement("results");
    outputDoc.appendChild(results);
    //NB! Each XML document is a tree, can only have one root

    //XPathExpression expr = path.compile("//description/text()");
    //XPathExpression expr = path.compile("//item/*/description/text()");
    //XPathExpression expr = path.compile("//item");
    XPathExpression expr = path.compile("//item[quantity>=8 and product/price/@currency='ZAR']");

    // NODESET means more than one node will be returned by the query
    NodeList resultSet = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    System.out.println("# nodes returned by query = " + resultSet.getLength());

    // unfortunately, the foreach notation does not work for the result set :(
    // i.e. for(Node node : resultSet)
    for (int i = 0; i < resultSet.getLength(); i++) {
        // attach item to root (if you want to use a node from one tree in another, you need to clone it first
        // as a node cannot belong to more than one tree at a time)
        Node node = resultSet.item(i).cloneNode(true);
        // associate the node with the output document
        outputDoc.adoptNode(node);
        // now allowed to attach the nodes together
        results.appendChild(node);
    }

    // get old root
    saveDoc(outputDoc, "items-output.xml");
}

Create New Document

public static Document createDoc() throws Exception {
    // create DocumentBuilder to parse XML document
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    // create empty document
    Document doc = builder.newDocument();

    return doc;
}

! ! ! ! XML File Building

import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.FileOutputStream;

public class Main {
        public static Document createDoc() throws Exception {
        // create DocumentBuilder to parse XML document
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        // create empty document
        Document doc = builder.newDocument();
        return doc;
    }

    public static void saveDoc(Document doc, String filename) throws Exception {
        // obtain serializer
        DOMImplementation impl = doc.getImplementation();
        DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
        LSSerializer ser = implLS.createLSSerializer();
        ser.getDomConfig().setParameter("format-pretty-print", true);
        // create file to save too
        FileOutputStream fout = new FileOutputStream("" + filename);
        // set encoding options
        LSOutput lsOutput = implLS.createLSOutput();
        lsOutput.setEncoding("UTF-8");
        // tell to save xml output to file
        lsOutput.setByteStream(fout);
        // FINALLY write output
        ser.write(doc, lsOutput);
        fout.close();
    }

    public static Element createTextElement(Document doc, String name, String text) {
        Text textNode = doc.createTextNode(text);
        Element element = doc.createElement(name);
        element.appendChild(textNode);
        return element;
    }

    public static Element createProduct(Document doc, String description, String price) {
        Element product = doc.createElement("product");
        product.appendChild(createTextElement(doc, "description", description));
        product.appendChild(createTextElement(doc, "price", price));
        return product;
    }

    public static Element createItem(Document doc, String description, String price, String quantity) {
        Element item = doc.createElement("item");
        item.appendChild(createProduct(doc, description, price));
        item.appendChild(createTextElement(doc, "quantity", quantity));
        return item;
    }

    /**
     * Creates and returns a document containing a number of items.
     */
    public static Document createItemDocument() throws Exception {
        Document doc = createDoc();

        Element items = doc.createElement("items");
        items.appendChild(createItem(doc, "Caramelo Bears", "5.25", "4"));
        items.appendChild(createItem(doc, "Jelly Tots", "1.24", "1000"));
        items.appendChild(createItem(doc, "Smarties", "2.35", "60"));
        doc.appendChild(items);

        return doc;
    }

    public static void main(String[] args) throws Exception {
        saveDoc(createItemDocument(), "output.xml");
    }
}