Java examples for XML:XML Element Child
get Child Elements By Name from XML Element
import java.util.ArrayList; import java.util.List; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main{ public static Element[] getChildElementsByName(Element parent, String name) throws XMLHelperException { Node[] nodes = getChildNodesByName(parent, name); Element[] elements = new Element[nodes.length]; for (int i = 0; i < nodes.length; i++) elements[i] = toElement(nodes[i]); return elements; }/*w w w .java 2s . co m*/ public static Node[] getChildNodesByName(Element parent, String name) { List<Node> nodeList = new ArrayList<Node>(); NodeList childNodes = parent.getChildNodes(); int length = childNodes.getLength(); for (int i = 0; i < length; i++) { Node current = childNodes.item(i); if (current.getNodeName().equals(name)) nodeList.add(current); } Node[] nodes = new Node[nodeList.size()]; nodeList.toArray(nodes); return nodes; } public static Element toElement(Node node) throws XMLHelperException { if (node.getNodeType() != Node.ELEMENT_NODE) throw new XMLHelperException("\"" + node.getNodeName() + "\" must be an element node"); return (Element) node; } }