59

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.

<THING1:things type="Container">
  <PART1:Id type="Property">1234</PART1:Id>
  <PART1:Name type="Property">The Name</PART1:Name>
</THING1:things>

It is a large file and there is much more to it than this but I hope this format will be familiar to someone. Does anyone know a way to approach an XML document of this sort?

I'd rather not just write a brute-force way of parsing the text but I can't seem to make any headway with REXML or Hpricot and I suspect it is due to these unusual tags.

my ruby code:

    require 'hpricot'
    xml = File.open( "myfile.xml" )

    doc = Hpricot::XML( xml )

   (doc/:things).each do |thg|
     [ 'Id', 'Name' ].each do |el|
       puts "#{el}: #{thg.at(el).innerHTML}"
     end
   end

...which is just lifted from: http://railstips.org/blog/archives/2006/12/09/parsing-xml-with-hpricot/

And I figured I would be able to figure some stuff out from here but this code returns nothing. It doens't error. It just returns.

n8gard
  • 1,870
  • 8
  • 26
  • 41
  • I take it line 1 is supposed to be , not type="Container">? – Benjamin Cox Jun 25 '12 at 22:45
  • Can you show us your Hpricot attempt? It _can_ handle namespaces, and it's easier and probably more instructive for us to help you figure out what's wrong with your attempt, rather than try to start you off fresh. – Benjamin Cox Jun 25 '12 at 23:09
  • I really don't have much of an attempt at this point. Just trying to emulate a tutorial. I will edit the post to include. – n8gard Jun 25 '12 at 23:18
  • 4
    For the record, hpricot is no longer being maintained. We're all using nokogiri now. – pguardiario Jun 26 '12 at 06:46
  • `THING1` and `PART1` are XML namespaces and are supposed to be declared. http://en.wikipedia.org/wiki/XML_namespace – Jonas Elfström Jun 27 '12 at 05:38

2 Answers2

92

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 = <<EOF
<THING1:things type="Container">
  <PART1:Id type="Property">1234</PART1:Id>
  <PART1:Name type="Property">The Name</PART1:Name>
</THING1:things>
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

Update

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

require 'nokogiri'

xml_str = <<EOF
<root>
  <THING1:things type="Container">
    <PART1:Id type="Property">1234</PART1:Id>
    <PART1:Name type="Property">The Name1</PART1:Name>
  </THING1:things>
  <THING2:things type="Container">
    <PART2:Id type="Property">2234</PART2:Id>
    <PART2:Name type="Property">The Name2</PART2:Name>
  </THING2:things>
</root>
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
digitalextremist
  • 5,952
  • 3
  • 43
  • 62
jmdeldin
  • 5,354
  • 1
  • 28
  • 21
  • This is great. I have it working for one item. It seems to pull the first item but not the others--as you said. Can you give an example of how to output all of the 'things'? There are about 10 of them. – n8gard Jun 27 '12 at 15:49
  • 1
    @B5Fan74 I have updated my answer with an example. Does that help? You need to add some kind of root element, which your XML file probably has. You then need to remove the // from the xpath query (or use the CSS interface, which I prefer). There's a [handy example](http://nokogiri.org/tutorials/searching_a_xml_html_document.html) in Nokogiri's docs on searching, so I hope that's useful too. – jmdeldin Jun 27 '12 at 22:01
  • Updating... Link moved to: https://www.engineyard.com/blog/getting-started-with-nokogiri – digitalextremist Nov 05 '17 at 06:28
  • `remove_namespaces!` saved me! Why is it sometimes necessary? – jayqui Oct 09 '20 at 00:27
  • 1
    @jayqui It all depends on your document, and how you're writing your selectors. The [documentation](https://www.rubydoc.info/github/sparklemotion/nokogiri/Nokogiri/XML/Document#remove_namespaces%21-instance_method) gives a little more info on the behavior. – jmdeldin Oct 09 '20 at 07:14
  • Running your first example gives `undefined method `at_xpath' for nil:NilClass` – reducing activity Mar 04 '21 at 11:09
  • @reducingactivity You're right! I guess Nokogiri has updated its handling in the last 9 years. I haven't worked in XML/Nokogiri in a long time, so from a quick IRB session, something like this could work, but it doesn't use xpath or anything smart. ``` doc.xpath("*").detect { |x| x.name =~ /:things\z/ }```. However, I think the correct solution is to define namespaces on each `THING` in the XML and update the Ruby code accordingly. The XML structure may need to change quite a bit. – jmdeldin Mar 04 '21 at 20:24
50

If in a Rails environment, the Hash object is extended and one can take advantage of the the method from_xml:

xml = File.open("myfile.xml")
data = Hash.from_xml(xml)
IliasT
  • 3,973
  • 1
  • 24
  • 26
  • 15
    `from_xml` is not a native Hash method, it's part of Rails / ActiveSupport. If you're in that environment, it works fine. – Trashpanda Jul 27 '16 at 03:09
  • 1
    this only works in rails environment, not working with plain ruby – Yakob Ubaidi May 23 '19 at 03:48
  • 11
    @YakobUbaidi note the first five words of the post. – IliasT May 23 '19 at 19:12
  • YMMV. This does not always convert child data structures that you expect/need to be hashes to hashes. It may instead convert those nested children to Arrays, in which case you lose the keys. – WillHaslett Mar 31 '21 at 16:31