Java tutorial
//package com.java2s; /* XMLUtils.java (c) 2010-2011 Edward Swartz All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html */ import java.util.ArrayList; import java.util.List; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Find or create a child element with the given name * @param element * @param name * @return new or existing element */ public static Element findOrCreateChildElement(Document document, Element element, String name) { Element[] elements = getChildElementsNamed(element, name); Element kid; if (elements.length > 0) { kid = elements[0]; } else { kid = document.createElement(name); element.appendChild(kid); } return kid; } /** * Get the elements with the given name. * @param element * @param name * @return array, never <code>null</code> */ public static Element[] getChildElementsNamed(Element element, String name) { if (element == null) return new Element[0]; NodeList nodeList = element.getChildNodes(); List<Element> elements = new ArrayList<Element>(); Node node = nodeList.item(0); while (node != null) { if (node instanceof Element && name.equals(node.getNodeName())) { elements.add((Element) node); } node = node.getNextSibling(); } return (Element[]) elements.toArray(new Element[elements.size()]); } }