質問

I'm reading in an XML file and recreating the structure for reprinting minus all attributes, values, and text. It's working fine as far as I can tell, but when I try to reprint it in the console I get very strange behavior.

for( xmlNode n : treeNodes )
    {
        System.out.println( n.getLabel() );
        printChildNodes( n, 1 );
    }


private static void printChildNodes( xmlNode n, int indent )
{
    for( int i = 0; i < indent; i++ )
    {
        System.out.print( indent );
    }

    for( xmlNode child : n.getChildren() )
    {
        System.out.println( child.getLabel() + " " + indent );
        printChildNodes( child, indent+1 );
    }
}

I get the following output

ROOT
1A 1
22B 2
333C 3
4444D 4
55555E 5
666666D 4
55555E 5
666666D 4
55555E 5
666666D 4

Originally instead of indent I was printing "\t" but I noticed the structure looked wrong. Now I'm scratching my head as to what possible ghost in the machine is resulting in my "indent" variable having two separate values with no changes made to it. Not to mention that the oddities are somewhat predictable. D elements should be to the left of E not to the right (since they are parents of E).

Any ideas?

役に立ちましたか?

解決

You only print the "indent" (actually a lot of numerics) once, at the start of the node's first line.

You then print children with a newline after each. The "indent" will only precede the first child.

You also don't print the node itself you are visiting, but only print the children. This is erroneous, and what with the node itself not showing up/ just a spurious indent, output will be very confusing when there are no children.

Additionally, you iterate over treeNodes and call into the printChildNodes function -- but that is recursive. Ideally I would only expect one recursive function to print & descend the entire subtree, with no loop.

printTree( rootNode, 0);

private static void printTree (xmlNode n, int indent) {
    StringBuilder ind = new StringBuilder();
    for (int i = 0; i < indent; i++)
        ind.append(' ');

    // print the Node;
    //
    System.out.println( ind + n.getLabel());

    // traverse Descendants.
    //
    for (xmlNode child : n.getChildren()) {
        printTree( child, indent+1);
    }
}

This should be pretty foolproof.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top