使用XPath查找节点中的最后一行

我想知道是否有办法总是选择某个元素上方的节点内容?

我有以下代码要提取:

Name

Some content1

Address 12345
09876 City, Country
12345

以下是查找范围上方所有内容的XPath:

 //div[@id="someDiv"]/span[@id="tel_number"]/preceding-sibling::node() 

现在,我需要的是一个XPath,它始终选择跨度上方的内容而不是其他内容(单行)。 如果(出于某种原因)缺少跨度,它也应该起作用。

希望有人可以帮忙!

尝试:

 (//div[@id="someDiv"]/span[@id="tel_number"]/preceding-sibling::text())[last()] 

或者如果你想删除空格

 normalize-space((//div[@id="someDiv"]/span[@id="tel_number"]/preceding-sibling::text())[last()]) 

我发现检索邮政编码的最佳方法如下:

 data = page.search('(//div[@id="someDiv"]/span[@id="tel_number"]/preceding-sibling::node()').map{|data| data.text.cleanup} data.delete("") postcode = data.last.match(/\d{5}/).to_s 

从那里可以轻松地在选择之后或之前检索所有内容。

我想检索“09876城市,国家”删除任何HTML标签

我认为下面你正在寻找:

 //div[@id="someDiv"]/span[@id="tel_number"]/preceding-sibling::text()[1] 

使用Nokogiri

 require 'nokogiri' doc = Nokogiri::HTML::Document.parse <<-EOT 

Name

Some content1

Address 12345
09876 City, Country
12345
EOT doc.xpath("normalize-space(//div[@id='someDiv']/span[@id='tel_number']/preceding-sibling::text()[1])").to_s # => "09876 City, Country"