如何使用Jericho HTML解析器遍历纯文本段 [英] How to iterate over plain text segments with the Jericho HTML parser

查看:96
本文介绍了如何使用Jericho HTML解析器遍历纯文本段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Jericho元素,我试图找出如何遍历所有子节点,无论是元素还是纯文本.

For a Jericho Element, I am trying to find out how to loop over all child nodes, whether an element or plain text.

现在有Element.getNodeIterator(),但这引用了Element中的所有后代,而不仅仅是第一个后代.

Now there is Element.getNodeIterator(), but this references ALL descendants within the Element, not just the first descendants.

我需要等价的Element.getChildSegments().有什么想法吗?

I need the equivalent of Element.getChildSegments(). Any ideas?

谢谢

推荐答案

所有纯文本段都不在任何子元素中,对吗?

All plain text segments not within any child elements, correct?

public static Iterator<Segment> directPlainTextChildren(Element elem) {
    final Iterator<Segment> it = elem.getContent().getNodeIterator();
    final List<Segment> results = new LinkedList<Segment>();
    final List<Element> children = elem.getChildElements();
    while (it.hasNext()) {
        Segment cur = it.next();
        if (!(cur instanceof Tag) && !(cur instanceof CharacterReference)) {
            for (Element child : children)
                if (child.contains(cur)) continue;
            results.add(cur);
        }
    }
    return results.iterator();
}

一个元素应该有几个直接子元素,而Element :: contains(Segment)方法只是一个简单的边界检查,因此性能应该足够.

An element should have few direct children and the Element::contains(Segment) method is just a simple bounds check, so the performance should be adequate.

如果您想添加迭代所有直接子段的功能,它将看起来像这样:

edit: If you wanted to add the ability to iterate all direct child segments it would look like this:

public static Iterator<Segment> getChildSegments(Element elem) {
    final Iterator<Segment> it = elem.getContent().getNodeIterator();
    final List<Segment> results = new LinkedList<Segment>();
    final List<Element> children = elem.getChildElements();
    while (it.hasNext()) {
        Segment cur = it.next();
        if (cur instanceof CharacterReference)
            results.add(cur);
        else if (cur instanceof Tag) {
            if (cur instanceof StartTag)
                results.add(((StartTag)cur).getElement());
        }
        else {
            for (Element child : children)
                if (child.contains(cur)) continue;
            results.add(cur);
        }
    }
    return results.iterator();
}

这篇关于如何使用Jericho HTML解析器遍历纯文本段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆