XML Examples

Example 1

public class Main {
    public static void main(String[] args) throws Exception {
        // example of how to load and query an XML document
        LoadAndQueryXML();

        // example of how to extract a selection of an existing XML document and add it to a
        // new XML document. the new XML document is then saved.
        CreateAndSaveXML();
    }

    private static void LoadAndQueryXML() throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        // 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();

        ///////////////////////////////////////////////////////////////////////////////////////////////////
        // examples of different queries
        ///////////////////////////////////////////////////////////////////////////////////////////////////

        // query document for the 1st item's quantity
        String result = path.evaluate("/items/item[1]/quantity", doc);
        System.out.println("quantity of product[1] = " + result);

        // query document for the currency of the 2nd item's product price
        result = path.evaluate("/items/item[2]/product/price/@currency", doc);
        System.out.println("currency of product[2] = " + result);

        // query document for the product description of any item of which there are 8
        result = path.evaluate("/items/item[quantity='8']/product/description", doc);
        System.out.println("product having quantity of 8 = " + result);

        // query document for the quantity of any item that has a product description of '4-port Mini Hub'
        result = path.evaluate("/items/item[product/description='4-port Mini Hub']/quantity", doc);
        System.out.println("quantity of '4-port Mini Hub' = " + result);

        // how many products are there? note // = any node with name product
        result = path.evaluate("count(//product)", doc);
        System.out.println("count of products = " + result);

        // how many products are there that have prices specified in ZAR amd the price is less than 30 ZAR?
        result = path.evaluate("count(//product[price/@currency='ZAR' and price < 30])", doc);
        System.out.println("count of products = " + result);
    }

    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);

        //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 and return an empty document.
     * @return The document that was created.
     * @throws Exception If something went wrong.
     */
    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;
    }

    /**
     * <p>Save the document to a file with the given filename.</p>
     * <p>You will be given the code for this method in a test, so you do not need to memorise it.</p>
     * @param doc The document to save.
     * @param filename The filename of the file to which the document will be saved.
     * @throws Exception If something goes wrong, e.g. invalid filename, not enough space, etc.
     */
    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);

        // close file
        fout.close();
    }
}

Example 2

public class Main {
    /**
     * A method that displays a specific element (and its children) indented on the console.
     *
     * @param element The element to display.
     * @param depth   The current indentation. Each child will be indented one level more than the parent.
     */
    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
                Element childElement = (Element) node;
                display(childElement, 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);
    }

    public static void main(String[] args) 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);

        // iterate through tree structure
        Element root = doc.getDocumentElement();
        display(root, 0);

        System.out.println();
        System.out.println();

        // obtain all nodes that have the tag name of 'description' and display them
        NodeList descriptions = root.getElementsByTagName("description");
        for (int i = 0; i < descriptions.getLength(); i++)
            display((Element) descriptions.item(i), 0);

    }
}

Example 3

public class Main {
    /**
     * Create an empty document.
     * @return The newly created document.
     * @throws Exception If cannot create the document for some reason.
     */
    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;
    }

    /**
     * <p>Save the document to a file with the given filename.</p>
     * <p>You will be given the code for this method in a test, so you do not need to memorise it.</p>
     * @param doc The document to save.
     * @param filename The filename of the file to which the document will be saved.
     * @throws Exception If something goes wrong, e.g. invalid filename, not enough space, etc.
     */
    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);

        // close file
        fout.close();
    }

    /**
     * <p>Creates, populates and returns an element that simply contains a text node. The element will have the
     * following format: &lt;name&gt;text&lt;/name&gt;</p>
     * @param doc The document to which this element belongs.
     * @param name The tag name for the element.
     * @param text The text contained by the element.
     * @return The newly created element.
     */
    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;
    }

    /**
     * <p>Creates, populates and returns a product element in the form <pre>
     *     &lt;product&gt;
     *          &lt;description&gt;description&lt;/product&gt;
     *          &lt;price&gt;price&lt;/price&gt;
     *     &lt;/product&gt;
     * </pre></p>
     * @param doc The document to which the element belongs.
     * @param description The description of the product.
     * @param price The price of the product.
     * @return The newly created product.
     */
    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;
    }

    /**
     * <p>Creates, populates and returns an item element. The element will contain a nested
     * product element, as well as a &lt;quantity&gt;quantity&lt;quantity&gt; element.</p>
     * @param doc The document to which the element belongs.
     * @param description The description of the product.
     * @param price The price of the product.
     * @param quantity The number of items of the given product type.
     * @return The newly created item.
     */
    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");
    }
}