我已經實現了一個快速和髒的替代getElementsByTagName
函數。它採用完全限定的標記名稱並返回所有具有確切標記名稱的後代元素節點。
/**
* Builds a list of the descendant elements with the supplied tag name from the {@code parent} node. The result
* nodes are ordered by a depth-first traversal of the element graph.
*
* @param tag {@link String} = The tag we are looking for. Fully qualified with the namespace if present (e.g. {@code hh:label})
* @param parent {@link Node} = Root node of the search
* @return {@link List<Node>} = The node list
*/
public static List<Node> getElementsByTagName(String tag, Node parent) {
List<Node> result = new ArrayList<>();
if (parent == null) {
return result;
}
NodeList children = parent.getChildNodes();
for (int childIdx = 0; childIdx < children.getLength(); childIdx++) {
Node child = children.item(childIdx);
if (child.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
if (((Element) child).getTagName() == tag) {
result.add(child);
}
getElementsByTagName(tag, child, result);
}
return result;
}
private static void getElementsByTagName(String tag, Node parent, List<Node> partialResult) {
if (parent == null) {
return;
}
NodeList children = parent.getChildNodes();
for (int childIdx = 0; childIdx < children.getLength(); childIdx++) {
Node child = children.item(childIdx);
if (child.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
if (((Element) child).getTagName() == tag) {
partialResult.add(child);
}
getElementsByTagName(tag, child, partialResult);
}
}