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>

したがって、基本的には、ルートノードから現在のタグの終わりまでのすべての文字の長さが必要です。残念ながら、その方法がわかりません。どんな助けでも感謝されるでしょう。前もって感謝します。

4

1 に答える 1

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

(ただし、変数とメソッドの名前をもう少し読みやすくするために再考することをお勧めします。)

于 2012-06-12T16:03:36.243 に答える