簡體   English   中英

如何使用Java來實現遍歷樹HTML的算法?

[英]How I can implement an algorithm that loops through a tree HTML with Java?

我必須走一棵從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();

.....

遞歸下降正是您要尋找的。

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

對於解析html,我過去使用過Jerry

它將自己標為Java的jquery,並允許您使用CSS樣式選擇器。 我認為現在有幾個庫現在可以實現CSS樣式選擇器。

盡管它可能不適合您的用例,但它會導致代碼更易於閱讀。

這是偽代碼

    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是樹的根節點。

像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM