Ruby - Nokogiri - Parsing XML from memory and putting all same name node values into an array.

Posted by r3nrut on Stack Overflow See other posts from Stack Overflow or by r3nrut
Published on 2010-12-21T22:36:42Z Indexed on 2010/12/22 2:54 UTC
Read the original article Hit count: 193

Filed under:
|
|

I have an XML I'm trying to parse from memory and get the status of each of my heart beat tests using Nokogiri. Here is the solution I have...

xml = 
<a:HBeat>
  <a:ElapsedTime>3 ms</a:ElapsedTime>
  <a:Name>Service 1</a:Name>
  <a:Status>true</a:Status>
</a:HBeat>
<a:HBeat>
  <a:ElapsedTime>4 ms</a:ElapsedTime>
  <a:Name>Service 2</a:Name>
  <a:Status>true</a:Status>
  </a:HBeat>
<a:HBeat>

I have tried using both css and xpath to pull back the value for each Status and put it into an array. Code is below:

doc = Nokogiri::XML.parse(xml)
#service_state = doc.css("a:HBeat, a:Status", 'a' => 'http://schemas.datacontract.org/2004/07/OpenAPI.Entity').map {|node| node.children.text}
service_state = doc.xpath("//*[@a:Status]", 'a' => 'http://schemas.datacontract.org/2004/07/OpenAPI.Entity').map(&:text)

Both will return service_state = []. Any thoughts or recommendations?

Also, consider that I have almost identical xml for another test and I used the following snippet of code which does exactly what I wanted but for some reason isn't working with the xml that contains namespaces.

service_state = doc.css("HBeat Status").map(&:text)

Thanks!

© Stack Overflow or respective owner

Related posts about ruby

Related posts about Xml