0

我正在尝试从 Weather Underground 的 XML 中提取一些信息。

我可以打开资源并提取所需的元素,但我真的想将元素text作为变量返回,不包含 XML 元素标签,因此我可以对其进行操作并将其显示在网页上。

也许有一种方法可以使用正则表达式去除标签,但我怀疑/希望我可以直接在 Nokogiri 中以更优雅的方式做到这一点。

目前我正在使用 irb 来计算语法:

irb>require 'rubygems'
irb>require 'nokogiri'
irb>require 'open-uri'
irb>doc = Nokogiri::XML(open('http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=KBHB'))
=> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
=> <?xml version="1.0"?>
# [...]
<!-- 0.036:0 -->

irb>doc.xpath('/current_observation/weather')
=> <weather>Clear</weather>irb(main):019:0> 
irb>doc.xpath('/current_observation/wind_dir')
=> <wind_dir>North</wind_dir>
irb>doc.xpath('/current_observation/wind_mph')
=> <wind_mph>10</wind_mph>
irb>doc.xpath('/current_observation/pressure_string')
=> <pressure_string>31.10 in (1053 mb)</pressure_string>

在使用以下结构时,我需要有关特定语法的帮助:

doc.xpath.element('/current_observation/weather')
doc.xpath.text('/current_observation/weather')
doc.xpath.node('/current_observation/weather')
doc.xpath.element.text('/current_observation/weather')

所有返回错误。

4

3 回答 3

1

根据 XPath,您可以返回带有text().

在您的示例中,它应该doc.xpath('/current_observation/weather/text()')获取weather's文本节点的内容。

于 2009-09-20T14:20:06.413 回答
0

One of the nice things about Nokogiri is its flexibility when writing accessors. You're not limited to XPath only, instead you can use CSS accessors:

require 'rubygems'
require 'nokogiri'
require 'open-uri'

doc = Nokogiri::XML(open('http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=KBHB'))

weather_report = %w[weather wind_dir wind_mph pressure_string].inject({}) { |h, n|
  h[n.to_sym] = doc.at('current_observation ' << n).text
  h 
} 
weather_report # => {:weather=>"Overcast", :wind_dir=>"South", :wind_mph=>"6", :pressure_string=>"29.67 in (1005 mb)"}
于 2011-03-12T10:13:51.383 回答
0

Something like this works for me:

irb(main):019:0> doc.xpath('//current_observation/weather').first.content
=> "Clear"
于 2009-09-20T14:10:49.537 回答