XML中的Java:递归返回节点

XML中的Java:递归返回节点,java,xml,dom,recursion,Java,Xml,Dom,Recursion,我有一个关于XML for Java中节点解析的问题 以下代码: public static String returnNodes(Node node, String node2) { // do something with the current node instead of System.out System.out.println("Test1: " + node.getNodeName()); String result = ""; result =

我有一个关于XML for Java中节点解析的问题

以下代码:

public static String returnNodes(Node node, String node2) {
    // do something with the current node instead of System.out
    System.out.println("Test1: " + node.getNodeName());
    String result = "";

    result = node.getNodeName();
    // Just for testing purposes
    if (result.equals(node2)) {
        return "YES!";
    }

    if (!result.equals(node2)) {
        System.out.println("Test2");
        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node currentNode = nodeList.item(i);
            if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
                //calls this method for all the children which is Element
                returnNodes(currentNode, node2);
            }
        }
    }

    return result;
}

如果我想以这种递归的方式打印出所需的节点,我需要更改什么?

我想回答我自己的问题。我所寻找的解决方案并不是真正的递归,而是迭代的,但会得到与我所寻找的相同的结果

public static String getNode(Document document, String search) {
    NodeList nodeList = document.getElementsByTagName("*");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(search)) {
            // do something with the current element
            return node.getNodeName();
        }
    }
    return null;
}
publicstaticstringgetnode(文档、字符串搜索){
NodeList NodeList=document.getElementsByTagName(“*”);
for(int i=0;i
public static String getNode(Document document, String search) {
    NodeList nodeList = document.getElementsByTagName("*");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(search)) {
            // do something with the current element
            return node.getNodeName();
        }
    }
    return null;
}