0

我必须走一棵从 NodeList 到达我的树,我需要一个算法来按顺序遍历所有节点,很可能是深入的,但不是如何实现它。我想我需要一些递归。有人可以帮忙吗?

部分代码为:NodeList nodeLista = documento.getElementsByTagName("html");

for (int s = 0; s < nodeLista.getLength(); s++) {
    Node Raiz = nodeLista.item(s);

……

    for (int h = 0; h < nodeLista.getLength(); h++) {

    //Level of depth 1.
    Node Primer_Hijo = nodeLista.item(h); // In the first iteration for the HEAD will enter in the second iteration enter the BODY.

    //Level of depth 2.
    Element SegundoElemento = (Element) Primer_Hijo;
    NodeList ListadeNodos2 = SegundoElemento.getChildNodes();

......

4

4 回答 4

0

递归下降正是您正在寻找的。

http://en.wikipedia.org/wiki/Recursive_descent_parser

于 2012-06-13T17:01:19.077 回答
0

对于解析 html,我过去使用过Jerry

它自称为 jquery for java 并允许您使用 css 样式选择器。我认为现在有几个库实现了 CSS 样式选择器。

尽管它可能不适合您的用例,但它会导致更易于阅读的代码。

于 2012-06-13T17:11:44.610 回答
0

这是伪代码

    traverse_tree(node)   {
    childNodes = node.getChildNodes();
    if(chidNodes is empty){
      print valueOf(node);
      return;
    }
    for each childNode in childNodes{
     traverse_tree(childNode);
    }
}

通过调用 traverse_tree(rootNode) 开始遍历 //root 是树的根节点。

于 2012-06-13T17:13:11.073 回答
0

像这样的东西:

public static void main(String[] args) {
    //get the nodeList
    //...
    for (int h = 0; h < nodeLista.getLength(); h++) {
        Node Primer_Hijo = nodeLista.item(h); 
        navegate(Primer_Hijo);
    }

    //or (better) the root node
    navegate(rootNode);
}

void navegate(Node node){
    //do something with node
    node.getAttributes();
    //...

    for(int i=0; i<node.getChildNodes().getLength(); i++)
        navegate(node.getChildNodes().item(i));
    }
}
于 2012-06-13T17:17:18.263 回答