Nokogiri从xml中提取数据

Nokogiri从xml中提取数据,xml,ruby-on-rails-3,nokogiri,Xml,Ruby On Rails 3,Nokogiri,我尝试使用Nokogiri gem从rails中的xml应用程序中提取数据 xml: <item> <description> <![CDATA[<img src="something" title="anothething"> <p>text, bla bla...</p>]]> </description> </item> 文本,等等…]> 实

我尝试使用Nokogiri gem从rails中的xml应用程序中提取数据

xml

<item>
    <description>
        <![CDATA[<img src="something" title="anothething">
        <p>text, bla bla...</p>]]>
    </description>
</item>

文本,等等…

]>
实际上,我这样做是为了从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
def测试内容
@return=Array.new
场地http://www.les-encens.com/modules/feeder/rss.php?id_category=0'
@doc=Nokogiri::XML(打开(站点,“UserAgent”=>“Ruby OpenURI”))
@doc.xpath(“//项”)。每个|

@return在Nokogiri中进行的xpath调用的结果将是a,这只是一个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

我的解决方案代码,感谢@Douglas和@Phrogz

def test_content
    site = 'xml-link'
    # On lit le xml généré par le site
    xml = Nokogiri::XML(open(site, "UserAgent" => "Ruby-OpenURI"))
    # On le converti en html
    xml = xml.to_html
    # On le lit a nouveau
    html = Nokogiri::HTML(xml)
    # on extrait les images
    @images = html.xpath('//img')
    # on stock leurs sources dans un tableau
    @images_sources = @images.map{|node| node['src']}
end

我可以建议
image\u sources=all\u images.map{node | node['src']}
比创建一个数组并将其推入其中更好、更惯用吗?当然可以。我尽量把代码弄清楚。对于地图上不是100%清楚的人来说,这可能有点混乱。但是我同意应该用惯用的方式来表示,稍微详细一点,内容是一个XML页面,并且在CDATA中,当我尝试这段代码时,我没有得到img src@Phrogz感谢map方法示例^^我尝试使用“Nokogiri::XML::ParseOptions.NOCDATA”,但它返回一个NoMethodErrorAwea-您可以提供一个示例片段(例如gist)或指向您尝试解析的文档的链接吗?
def test_content
    site = 'xml-link'
    # On lit le xml généré par le site
    xml = Nokogiri::XML(open(site, "UserAgent" => "Ruby-OpenURI"))
    # On le converti en html
    xml = xml.to_html
    # On le lit a nouveau
    html = Nokogiri::HTML(xml)
    # on extrait les images
    @images = html.xpath('//img')
    # on stock leurs sources dans un tableau
    @images_sources = @images.map{|node| node['src']}
end