Parsing simple XML with Nokogiri

后端 未结 2 1269
醉梦人生
醉梦人生 2021-02-02 14:04

I have the following XML:



  
    Title 1
    http://www.example.com/url-1
  

        
相关标签:
2条回答
  • 2021-02-02 14:42

    The trouble here is that the Xpath //title searches for titles from the root of the document, and so returns all title tags. Using the Xpath title searches within the context of the given node, like you want. Ditto on url.

    @links = doc.xpath('//links/item').map do |i|
      {'title' => i.xpath('title'), 'url' => i.xpath('url')}
    end
    
    0 讨论(0)
  • 2021-02-02 14:58

    Replace this:

    @links = doc.xpath('//links/item').map do |i| 
      {'title' => i.xpath('//title'), 'url' => i.xpath('//url')} 
    

    with:

    @links = doc.xpath('//links/item').map do |i| 
      {'title' => i.xpath('title'), 'url' => i.xpath('url')} 
    

    Explanation:

    //title 
    

    and

    //url
    

    are absolute XPath expressions and they select all (respectively) title and all url elements in the XML document.

    Contrast this with:

    title
    

    and

    url
    

    These are relative XPath expressions and select all (respectively) title and url children of the current node only.

    0 讨论(0)
提交回复
热议问题