Java tutorial
//package com.java2s; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Creates (only if necessary) and returns the element which is at the end of the specified * path. * * @param doc * the target document where the specified path should be created * @param path * a dot separated string indicating the path to be created * @return the component at the end of the newly created path. */ public static Element createLastPathComponent(Document doc, String[] path) { Element parent = (Element) doc.getFirstChild(); if (path == null || parent == null || doc == null) { throw new IllegalArgumentException("Document parent and path must not be null"); } Element e = parent; for (int i = 0; i < path.length; i++) { Element newEl = getChildElementByTagName(e, path[i]); if (newEl == null) { newEl = doc.createElement(path[i]); e.appendChild(newEl); } e = newEl; } return e; } /** * Returns the child element with the specified tagName for the specified parent element * * @param parent * @param tagName * @return */ public static Element getChildElementByTagName(Element parent, String tagName) { if (parent == null || tagName == null) { return null; } NodeList nodes = parent.getChildNodes(); Node node; int len = nodes.getLength(); for (int i = 0; i < len; i++) { node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE && ((Element) node).getNodeName().equals(tagName)) { return (Element) node; } } return null; } }