【问题标题】:How to write an XPath query to match two attributes?如何编写 XPath 查询来匹配两个属性?
【发布时间】:2011-01-01 19:54:35
【问题描述】:

以下问题:

<div id="id-74385" class="guest clearfix" style="z-index: 999;">

如上所述,

如果我想要一个同时检查 id 和 class 的 XPath 表达式,我们可以使用“和”条件 LIKE 来实现吗:

//div[@id='id-74385'] and div[@class='guest clearfix']

这是正确的方法吗?我在这里执行失败...请帮助!

【问题讨论】:

    标签: xpath


    【解决方案1】:
    //div[@id='..' and @class='...]
    

    应该可以解决问题。即选择具有所需值的 both 属性的 div 运算符。

    值得使用online XPath testbeds 之一来尝试一下。

    【讨论】:

    • 许多在线工具都要求符合 XML。对于 HTML,使用浏览器的 XPath 实现更容易测试。这是一个code sample,以及一个将迭代器转换为数组的辅助函数。
    【解决方案2】:

    //div[@id='id-74385'][@class='guest clearfix']

    【讨论】:

      【解决方案3】:

      示例 XML:

      <X>
      <Y ATTRIB1=attrib1_value ATTRIB2=attrib2_value/>
      </X>
      
      string xPath="/" + X + "/" + Y +
      "[@" + ATTRIB1 + "='" + attrib1_value + "']" +
      "[@" + ATTRIB2 + "='" + attrib2_value + "']"
      

      XPath 测试平台: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm

      【讨论】:

        【解决方案4】:

        添加到 Brian Agnew 的答案。

        您也可以使用//div[@id='..' or @class='...],并且您可以在//div[@id='..' and (@class='a' or @class='b')] 中使用带括号的表达式。

        【讨论】:

          猜你喜欢
          • 2020-03-24
          • 1970-01-01
          • 1970-01-01
          • 2016-04-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多