これが私が解決しようとしている問題です。簡単な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>
したがって、基本的には、ルートノードから現在のタグの終わりまでのすべての文字の長さが必要です。残念ながら、その方法がわかりません。どんな助けでも感謝されるでしょう。前もって感謝します。