如何通过XPath选择第一个元素? [英] How to select first element via XPath?

查看:2506
本文介绍了如何通过XPath选择第一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下HTML结构

I have the following HTML structure

<div class="carousel">
  <ul class ="carousel-view">
    <li>
      <figure>
        <a id="one"/>
      </figure>
    </li>
    <li>
      <figure>
        <a id="two"/>
      </figure>
    </li>
  </ul>
</div>

如何使用XPath访问第一个a元素?请注意,列表中有多个a元素.

How do I use XPath to access the first a element? Notice there are multiple a elements inside the list.

推荐答案

这些XPath表达式中的任何一个都会选择第一个a元素:

Any of these XPath expressions will select the first a element:

  • (//a)[1]选择整个文档中的第一个a.
  • (/div/ul/li/figure/a)[1]选择具有显示的遗产的第一个a.
  • (//div[@class='carousel']/ul/li/figure/a)[1]限制了遗产.
  • (//div[@class='carousel']//a)[1]提取一些遗产.
  • (//a)[1] selects first a in the whole document.
  • (/div/ul/li/figure/a)[1] selects first a with shown heritage.
  • (//div[@class='carousel']/ul/li/figure/a)[1] restricts heritage.
  • (//div[@class='carousel']//a)[1] abstracts away some heritage.

根据实际文档中显示的XML的上下文以及是否希望将a元素限制为仅在某些其他元素下的元素来进行选择.

Choose depending upon the context of your shown XML in your actual document and whether you wish to restrict the a elements to only those under certain other elements.

请注意,//a[1]实际上选择了 多个 a个元素:

Note that //a[1] actually selects multiple a elements:

<a id="one"/>
<a id="two"/>

因为//a[1]表示选择a元素是其父元素的第一个子元素.

because //a[1] means select the a elements that are the first child of its parent.

您必须使用括号(//a)[1]进行选择

You must use parentheses (//a)[1] to select

<a id="two"/>

单独作为文档中的第一个a.

alone as the first a in the document.

这篇关于如何通过XPath选择第一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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