Awe*_*wea 2 xml nokogiri ruby-on-rails-3
我尝试使用Nokogiri gem从rails应用程序中的xml中提取数据,
xml:
<item>
<description>
<![CDATA[<img src="something" title="anothething">
<p>text, bla bla...</p>]]>
</description>
</item>
Run Code Online (Sandbox Code Playgroud)
实际上我做这样的事情从xml中提取数据:
def test_content
@return = Array.new
site = 'http://www.les-encens.com/modules/feeder/rss.php?id_category=0'
@doc = Nokogiri::XML(open(site, "UserAgent" => "Ruby-OpenURI"))
@doc.xpath("//item").each do |n|
@return << [
n.xpath('description')
]
end
end
Run Code Online (Sandbox Code Playgroud)
你能告诉我如何从img标签中提取src属性吗?
编辑: 我已用正确的替换xml.
在Nokogiri中进行的xpath调用的结果将是一个NodeSet,它只是一个Nokigiri 节点列表
考虑到这一点,我们可以从Nokogiri文档中提取示例并进行调整.
要回答你的问题,"你能告诉我如何从img标签中提取src属性吗?" ,这是一种这样的方式.
#the 'open' method here is part of the open-uri library
xml = Nokogiri::XML(open(your_url_here))
all_images = xml.xpath("//img") #returns NodeSet (list of Nokogiri Nodes)
image_sources = []
#iterate through each node
all_images.each() do |node|
image_sources << node.get_attribute('src') #One method
#image_sources << node['src'] #Another convention we could use
end
Run Code Online (Sandbox Code Playgroud)
正如Phrogz在下面所指出的,从所有图像节点中拉出'src'属性的更加自觉的方法是直接映射'src'属性,而不是迭代并推送到数组.
image_sources = all_images.map{ |node| node['src'] }
Run Code Online (Sandbox Code Playgroud)