2012-06-12 14 views
2

以下是我正在嘗試解決的問題。 我有一個簡單的HTML頁面:步行樹 - 標記值的長度

<html> 
<head></head> 
<body> 
    <table> 
     <tr> 
      <td>Hello</td> 
      <td>World</td> 
     </tr> 
     <tr> 
      <td>Goodby</td> 
      <td>World</td> 
     </tr> 
    </table> 
</body> 

我想要做的,是通過整個樹走路和存儲每個文本節點的長度。它不僅應該包含當前節點的長度,而且實際上可以添加到所有以前的文本節點的長度。讓我澄清我的意思這個例子:

<html> 
<head></head> 
<body> 
    <table> 
     <tr> 
      <td>Hello</td> // console output should be string of length: 5 
      <td>World</td> // console output should be string of length: 10 
     </tr> 
     <tr> 
      <td>Goodby</td> // console output should be string of length: 16 
      <td>World</td> // console output should be string of length: 21 
     </tr> 
    </table> 
</body> 

對於我實現下面的代碼:

private static void print(Node aNode, int aCounter, String aIndent) 
{ 
    if(aNode.getNodeValue() != null) 
     System.out.println(aIndent+aNode.getNodeName() + ", "+aNode.getNodeValue() + ", length: " + aCounter); 
    else 
     System.out.println(aIndent+aNode.getNodeName()); 

    Node child = aNode.getFirstChild(); 

    while (child != null) 
    { 
     if(child.getNodeValue() != null) 
     { 
      aCounter += child.getNodeValue().length(); 
      print(child, aCounter, aIndent+" "); 
     } 
     else 
      print(child, aCounter, aIndent+" "); 

     child = child.getNextSibling(); 
    } 
} 

我通過根節點這種方法。這個代碼的問題是它只返回一個路徑的長度。這意味着我得到的是這樣的:

<html> 
<head></head> 
<body> 
    <table> 
     <tr> 
      <td>Hello</td> // console output is string of length: 5 
      <td>World</td> // console output is string of length: 10 
     </tr> 
     <tr> 
      <td>Goodby</td> // console output should be string of length: 6 <-- does not consider overall length of previous <tr> content 
      <td>World</td> // console output should be string of length: 11 
     </tr> 
    </table> 
</body> 

所以基本上我想從根節點到當前標籤的末尾所有字符的長度。不幸的是我不知道該怎麼做。任何幫助都會受到歡迎。先謝謝你。

回答

1

aCounter通過值傳遞(不是通過引用),所以從遞歸調用方法向其中添加值不會影響調用方法中的值。您可能想要將新值aCounter返回給調用方法,以便它可以更新其自己的版本。

像這樣的東西應該工作:

private static void print(Node aNode, int aCounter, String aIndent) 
{ 
    if(aNode.getNodeValue() != null) 
     System.out.println(aIndent+aNode.getNodeName() + ", "+aNode.getNodeValue() + ", length: " + aCounter); 
    else 
     System.out.println(aIndent+aNode.getNodeName()); 

    Node child = aNode.getFirstChild(); 

    while (child != null) 
    { 
     if(child.getNodeValue() != null) 
     { 
      aCounter += child.getNodeValue().length(); 
     } 
     aCounter = print(child, aCounter, aIndent+" "); 

     child = child.getNextSibling(); 
    } 

    return aCounter; 
} 

(雖然你可能要重新考慮你的變量和方法的名稱,使其多一點可讀性。)

+0

感謝馬蒂亞斯!就是這樣。我也遵循你的建議,選擇更有意義的方法/變量名稱。 – user1451602

+0

如果答案解決了您的問題,[您應該接受它](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。只需點擊答案左側的複選標記即可。 ;-) –