Parsing XML with Ruby

后端 未结 2 810
野的像风
野的像风 2020-12-05 01:53

I\'m way new to working with XML but just had a need dropped in my lap. I have been given an usual (to me) XML format. There are colons within the tags.

<         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 02:22

    As @pguardiario mentioned, Nokogiri is the de facto XML and HTML parsing library. If you wanted to print out the Id and Name values in your example, here is how you would do it:

    require 'nokogiri'
    
    xml_str = <
      1234
      The Name
    
    EOF
    
    doc = Nokogiri::XML(xml_str)
    
    thing = doc.at_xpath('//things')
    puts "ID   = " + thing.at_xpath('//Id').content
    puts "Name = " + thing.at_xpath('//Name').content
    

    A few notes:

    • at_xpath is for matching one thing. If you know you have multiple items, you want to use xpath instead.
    • Depending on your document, namespaces can be problematic, so calling doc.remove_namespaces! can help (see this answer for a brief discussion).
    • You can use the css methods instead of xpath if you're more comfortable with those.
    • Definitely play around with this in irb or pry to investigate methods.

    Resources

    • Parsing an HTML/XML document
    • Getting started with Nokogiri

    Update

    To handle multiple items, you need a root element, and you need to remove the // in the xpath query.

    require 'nokogiri'
    
    xml_str = <
      
        1234
        The Name1
      
      
        2234
        The Name2
      
    
    EOF
    
    doc = Nokogiri::XML(xml_str)
    doc.xpath('//things').each do |thing|
      puts "ID   = " + thing.at_xpath('Id').content
      puts "Name = " + thing.at_xpath('Name').content
    end
    

    This will give you:

    Id   = 1234
    Name = The Name1
    
    ID   = 2234
    Name = The Name2
    

    If you are more familiar with CSS selectors, you can use this nearly identical bit of code:

    doc.css('things').each do |thing|
      puts "ID   = " + thing.at_css('Id').content
      puts "Name = " + thing.at_css('Name').content
    end
    

提交回复
热议问题