使用XHTML文档中的grails中的JSOUP获取两个不同标记之间的文本

时间:2014-11-25 15:25:21

标签: html grails tags xhtml jsoup

我想在我的xhtml文档中获取标记ae_definedtermtitlebegin的所有文本。此标记在整个文档中出现1000次。我正在尝试创建与此标记关联的文本列表。我正在使用JSOUP和grails。代码到目前为止已经写了

Document doc = Jsoup.parse(file,"UTF-8")
Elements pres = doc.getElementsByTag("ae_definedTermTitleBegin");
println pres //This prints a list which contains the tag itself fr eg. [<ae_definedtermtitlebegin/>,<ae_definedtermtitlebegin/>,<ae_definedtermtitlebegin/>....]
for (Element pre : pres) {
    println pre.text() //prints nothing. I assumed this would print the text within the tag
}           

感谢您的帮助。真的很感激。 在xhtml文档中,文本看起来像

<ae_definedTermTitleBegin />Applicable Permitted Investment
Amount<ae_definedTermTitleEnd />

我知道我的内容介于两个不同的标签之间。如何在这两个标签之间获取文本?

1 个答案:

答案 0 :(得分:0)

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;

public class Main {

    public static void main(String[] args) throws Exception {
    /*  String html =   "<ae_definedTermTitleBegin />" +
                            "Applicable Permitted Investment Amount" +
                        "<ae_definedTermTitleEnd />";
    */
        String html = "<ae_definedTermTitleBegin />" +
                        "Applicable Permitted Investment Amount" +
                        "<ae_definedTermTitleBegin />" +
                            "Inner example" +
                        "<ae_definedTermTitleEnd />" +
                        "This is harder" +
                       "<ae_definedTermTitleEnd />";

        Document doc = Jsoup.parse(html);
        List<TextNode> lines = getTextBetweenTags(doc.getElementsByTag("body").get(0).childNodes(), 
                                                    "ae_definedTermTitleBegin", "ae_definedTermTitleEnd");

        System.out.println(lines);
    }

    private static List<TextNode> getTextBetweenTags(List<Node> listOfNodes, String tagStart, String tagEnd) {

        List<TextNode> lines = new ArrayList<>();

        int inRangeCounter = 0;
        for(Node node : listOfNodes) {
            if(node.nodeName().equalsIgnoreCase(tagStart)) {
                inRangeCounter++;
            } else if(node.nodeName().equalsIgnoreCase(tagEnd)) {
                inRangeCounter--;
            } else if(inRangeCounter > 0 && node instanceof TextNode) {
                lines.add((TextNode)node);
            }
        }

        return lines;
    }
}