
<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
总结以上是内存溢出为你收集整理的ruby – XPath查找所有后续兄弟姐妹直到特定类型的下一个兄弟全部内容,希望文章能够帮你解决ruby – XPath查找所有后续兄弟姐妹直到特定类型的下一个兄弟所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)