私は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);
}
}