Here you can find the source of getChildElementsByTagName(Element parentNode, String tagName)
parentNode
and with the same tag name of tagName
; it's not deep search, so only the first generation children list is scanned tagName
is just local name; namespace is not support right now.
Parameter | Description |
---|---|
parentNode | a parameter |
tagName | a parameter |
Parameter | Description |
---|---|
DOMException | an exception |
public static List<Element> getChildElementsByTagName(Element parentNode, String tagName)
//package com.java2s; import java.util.ArrayList; import java.util.List; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /**//from w w w. j a va2 s . c o m * return all the child Elements under given Element <code>parentNode</code> and with the same tag name of <code>tagName</code> ; * it's not deep search, so only the first generation children list is scanned <br/>Note: the given <code>tagName</code> is just local * name; namespace is not support right now. * * @param parentNode * @param tagName * @return * @throws DOMException */ public static List<Element> getChildElementsByTagName(Element parentNode, String tagName) { if (parentNode == null) { return null; } // if there is no tag name given, treat it as returning all the child Elements if (tagName == null || tagName.trim().length() == 0) { return getChildElements(parentNode); } List<Element> resultList = new ArrayList<Element>(); NodeList childNodes = parentNode.getChildNodes(); if (childNodes != null) { for (int i = 0; i < childNodes.getLength(); i++) { Node node = childNodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE && node.getParentNode() == parentNode && node.getLocalName().equals(tagName)) { resultList.add((Element) node); } } } return resultList; } /** * return all the child Elements of given Element; it's not deep search, so only the first generation children list is scanned. * * @param parentNode * @return an empty list if nothing found * @throws DOMException */ public static List<Element> getChildElements(Element parentNode) throws DOMException { if (parentNode == null) { return null; } List<Element> resultList = new ArrayList<Element>(); NodeList childNodes = parentNode.getChildNodes(); if (childNodes != null) { for (int i = 0; i < childNodes.getLength(); i++) { Node node = childNodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE && node.getParentNode() == parentNode) { resultList.add((Element) node); } } } return resultList; } }