jsoup:如何select直接parents直到根无兄弟姐妹?

Jsoup: How to select direct parents until the root without their siblings?

我正在尝试获取所有直接 parents 元素,但我也获取了它们的兄弟姐妹。

比如我有这个DOM结构...

<div class="html">
  <div class="head"></div>
  <div class="body">
    <a href="seznam.cz">seznam</a>
    <h2>Foo</h2> 
    <a href="google.com">google</a> 
    <p>
      <img class="first">
    </p>
    <img class="second"> 
    <ol>
      <li>1</li>
      <li>2</li>
    </ol>
  </div>
</div>

所以我想得到 img 元素的所有直接 parents class first 直到 div 与 class html.

我试过使用以下代码

Element element = document.select("img").first();
Node root = element.root();

但是在根变量中我得到了整个 DOM 结构以及所有兄弟姐妹。

更新

在 root var 之后,我又拥有了整个 DOM 结构:

<div class="html">
  <div class="head"></div>
  <div class="body">
    <a href="seznam.cz">seznam</a>
    <h2>Foo</h2> 
    <a href="google.com">google</a> 
    <p>
      <img class="first">
    </p>
    <img class="second"> 
    <ol>
      <li>1</li>
      <li>2</li>
    </ol>
  </div>
</div>

但我想要这样的东西:

<div class="html">
  <div class="body"> 
    <p>
      <img class="first">
    </p>
  </div>
</div>

首先使用

获取名称为 'first' 的所有元素 class
Elements childs = document.getElementsByClass("first");

现在,迭代所有子元素以获取它们的父元素,

    for( Element child : childs){
      Elements parents = child.parents();
      for(Element parent: parents){
        System.out.println(parent.tagName());
      }
    }

试试这个,希望它对你有用;)

如果您只对路径感兴趣,请使用 Element.cssSelector()

它为您提供完整的 DOM 路径,例如html > body > img

"Path" Darshit Chokshi 返回的方法不是唯一的。