ruby – XPath查找所有后续兄弟姐妹直到特定类型的下一个兄弟
发布时间:2020-12-17 02:53:32 所属栏目:百科 来源:网络整理
导读:鉴于此 XML / HTML: dl dtLabel1/dtddValue1/dd dtLabel2/dtddValue2/dd dtLabel3/dtddValue3a/ddddValue3b/dd dtLabel4/dtddValue4/dd/dl 我想找到所有 dt然后,对于每个,找到以下 dd直到下一个 dt. 使用Ruby的Nokogiri我可以这样做: dl.xpath('dt').each
鉴于此
XML / HTML:
<dl> <dt>Label1</dt><dd>Value1</dd> <dt>Label2</dt><dd>Value2</dd> <dt>Label3</dt><dd>Value3a</dd><dd>Value3b</dd> <dt>Label4</dt><dd>Value4</dd> </dl> 我想找到所有< dt>然后,对于每个,找到以下< dd>直到下一个< dt>. 使用Ruby的Nokogiri我可以这样做: dl.xpath('dt').each do |dt| ct = dt.xpath('count(following-sibling::dt)') dds = dt.xpath("following-sibling::dd[count(following-sibling::dt)=#{ct}]") puts "#{dt.text}: #{dds.map(&:text).join(',')}" end #=> Label1: Value1 #=> Label2: Value2 #=> Label3: Value3a,Value3b #=> Label4: Value4 但是,正如您所看到的,我在Ruby中创建一个变量,然后使用它编写一个XPath.我怎样才能编写一个相同的XPath表达式? 我猜到: following-sibling::dd[count(following-sibling::dt)=count(self/following-sibling::dt)] 但显然我不明白那里的自我意味着什么. 此问题类似于XPath : select all following siblings until another sibling,但“停止”节点没有唯一标识符. 这个问题与xpath to find all following sibling adjacent nodes up til another type几乎相同,只是我要求一个仅限XPath的解决方案. 解决方法
一种可能的方案:
dl.xpath('dt').each_with_index do |dt,i| dds = dt.xpath("following-sibling::dd[not(../dt[#{i + 2}]) or " + "following-sibling::dt[1]=../dt[#{i + 2}]]") puts "#{dt.text}: #{dds.map(&:text).join(',')}" end 这依赖于dt元素的值比较,并且当存在重复时将失败.以下(更复杂的)表达式不依赖于唯一的dt值: following-sibling::dd[not(../dt[$n]) or (following-sibling::dt[1] and count(following-sibling::dt[1]|../dt[$n])=1)] 注意:您使用self失败是因为您没有正确使用它作为轴(self::).另外,self总是只包含上下文节点,所以它会引用由表达式检查的每个dd,而不是返回原来的dt (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- 如何从给定格式的dijit.form.DateTextBox获取日期
- c# – 如何使用密码连接到sqlite数据库
- EnterpriseDB's index advisor
- SOLR 中 Schema.xml 的filedType 的一些属性的理
- Postgresql运算符类“varchar_pattern_ops”不接
- Qt4.5.1触摸屏(tslib 1.4)+sqlite3 移植全记录
- Oracle中查看引起Session阻塞的2个脚本分享
- 详解基于 axios 的 Vue 项目 http 请求优化
- 什么是xmlns:XSD中的mstns?
- c# – 如何将2个Guids转换为最多50个字符长度的字
热点阅读