Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get attribute value from XML

Tags:

ruby

nokogiri

I have this chunk of XML:

<show name="Are We There Yet?">
  <sid>24588</sid>
  <network>TBS</network>
  <title>The Kwandanegaba Children's Fund Episode</title>
  <ep>03x31</ep>
  <link>
    http://www.tvrage.com/shows/id-24588/episodes/1065228407
  </link>
</show>

I am trying to get "Are we there yet?" via Nokogiri. It is effectively the 'name' attribute of 'show'. I'm struggling to figure out how to parse this.

xml.at_css('show').value was my best guess but doesn't work.

like image 729
John R Avatar asked Nov 21 '25 01:11

John R


2 Answers

You can use the following:

xml.at('//show/@name').text

which is XPath expression that returns the name attribute from the show element.

like image 74
Mark Thomas Avatar answered Nov 24 '25 00:11

Mark Thomas


Use:

require 'nokogiri'

xml =<<EOT
<show name="Are We There Yet?">
  <sid>24588</sid>
  <network>TBS</network>
  <title>The Kwandanegaba Children's Fund Episode</title>
  <ep>03x31</ep>
  <link>
    http://www.tvrage.com/shows/id-24588/episodes/1065228407
  </link>
</show>
EOT

xml = Nokogiri::XML(xml)
puts xml.at('show')['name']
=> Are We There Yet?

at accepts either CSS or XPath expressions, so feel free to use it for both. Use at_css or at_xpath if you know you need to declare the expression as CSS or XPath, respectively. at returns a Node, so you can simply reference the parameters of the node like you would a hash.

like image 42
the Tin Man Avatar answered Nov 23 '25 22:11

the Tin Man



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!