2014-10-30 136 views
0

我有一個問題,關於解析Java for XML中的節點。Java中的XML:遞歸返回節點

以下代碼:

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; 
} 

我想證明,如果node2等於當前node和 - 如果它匹配 - 返回一個變量,名爲結果值。 目前我只是得到我的文檔的根元素,如果我調用這個方法,我不知道爲什麼。但是,「是!」從未打印在我的控制檯上,但System.out.println("Test1: " + node.getNodeName());會打印「演員」,如果我以這種方式調用該方法: returnNodes(document.getFirstChild(), "actor"); - 因此結果總是「記錄」。

的XML的結構是這樣的:

<?xml version="1.0" encoding="UTF-8" ?> 
<log> 
<published>2014-03-28T15:28:36.646Z</published> 
<actor> 
    <objectType>person</objectType> 
    <id>e1b8948f-321e-78ca-d883-80500aae71b5</id> 
    <displayName>anonymized</displayName> 
</actor> 
<verb>update</verb> 
<object> 
    <objectType>concept</objectType> 
    <id>a1ad6ace-c722-ffa9-f58e-b4169acdb4e3</id> 
    <content>time</content> 
</object> 
<target> 
    <objectType>conceptMap</objectType> 
    <id>4b8f69e3-2914-3a1a-454e-f4c157734bd1</id> 
    <displayName>my first concept map</displayName> 
</target> 
<generator> 
    <objectType>application</objectType> 
    <url>http://www.golabz.eu/content/go-lab-concept-mapper</url> 
    <id>c9933ad6-dd4a-6f71-ce84-fb1676ea3aac</id> 
    <displayName>ut.tools.conceptmapper</displayName> 
</generator> 
<provider> 
    <objectType>ils</objectType> 
    <url>http://graasp.epfl.ch/metawidget/1/b387b6f</url> 
    <id>10548c30-72bd-0bb3-33d1-9c748266de45</id> 
    <displayName>unnamed ils</displayName> 
</provider> 
</log> 

我有什麼改變,如果我想打印出我需要在這個循環方式的節點?

回答

0

我想回答我自己的問題。我尋找的解決方案並不是真正的遞歸,而是迭代的,但導致我尋找的結果相同。

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; 
}