我如何在 JSoup 中 select "this element" 的直接子代

How do I select a direct child of "this element" in JSoup

如果我有一个看起来像这样的元素:

<foo>
    <bar> bar text 1 </bar>
    <baz>
        <bar> bar text 2 </bar>
    </baz>
</foo>

而且我已经 <foo> 元素 selected,我想 select <bar> 元素是 <foo> 的直接子元素但不是 <baz> 的子项,我该如何指定?

Element foo = <that thing above>
foo.select("bar").text();

产量"bar text 1 bar text 2"

我想要的是

foo.select("this > bar").text();

问题是:如何在select或[=22中指定"this element" =]

请注意,所需的 bar 可能不是第一个 -- 我需要一个也适用于:

的解决方案
<foo>
    <baz>
        <bar> bar text 2 </bar>
    </baz>
    <bar> bar text 1 </bar>
</foo>

使用:root结构伪元素指定"this element"。从Element.select Javadoc,我们看到select使用"this element as the starting context",可以匹配"this element, or any of its children";也就是说,:root 指的是 this 元素,而不是实际的文档根。下面的代码通过将第二个示例放在一些外部标记中进行演示:

//nest your second sample in some fake outer html body
Element html = (Element)Parser.parseFragment("<html><body><foo>\n" +
                "    <baz>\n" +
                "        <bar> bar text 2 </bar>\n" +
                "    </baz>\n" +
                "    <bar> bar text 1 </bar>\n" +
                "</foo></body></html>", null, "http://example.com").get(0);
Element foo = html.select("foo").first();

System.out.println(foo.select(":root > bar"));

此代码打印

<bar>
  bar text 1 
</bar>

正确跳过嵌套的 bar 元素。

根据Jsoup changelog,在1.7.2中添加了结构伪元素支持。

我相信你想要:

foo.select("> bar").text();

查看 jsoup Selectors 页面,Combinators 部分:

E > F     an F direct child of E