Question

I am using libxml-ruby gem to read a xml string.

I am unable to extract the required info from xml string.

Currently i have following xml

<?xml version="1.0" encoding="utf-8"?>
<message>
  <head>
    <api_key>252f5df2df522fg5fd25df2df5df2fd5</api_key>
    <user>123</user>
    <secret>********************</secret>
    <signature>****************</signature>
    <synchronization token="kj0s09ew090mv904v09409905b" last_synchronize_on="2010-01-02 11:30" />
  </head>
  <blockings>
    <blocking token="AAA" start_time="2010-01-01 10:00" end_time="2010-01-01 12:00" method="REQUEST" is_forced="FALSE" />
    <blocking token="BBB" start_time="2010-01-03 15:00" end_time="2010-01-03 18:00" method="REQUEST" is_forced="FALSE" />
  </blockings>
</message>

How do i get api_key, synchronization token, last_synchronize_on values from this xml string?

How do i get the info of the blocking nodes inside blockings node of this string?

Thanks

Was it helpful?

Solution

You'd use LibXML::XML::Parser to get a LibXML::XML::Document:

p = LibXML::XML::Parser.file(xml_file)
# or p = LibXML::XML::Parser.string(xml_string)
doc = p.parse

Then use find and a bit of XPath to find your nodes:

api_key_node = doc.find('//api_key').first

That gives you a LibXML::XML::Node in api_key_node so you can call content to get what you want:

api_key = api_key_node.content
# "252f5df2df522fg5fd25df2df5df2fd5"

Similar things apply to synchronization but you'd use [] to access the attribute values:

sync      = doc.find('//synchronization').first
token     = sync['token']
last_sync = sync['last_syncrhonize_on']

Same deal again for the <blocking> nodes but you'd iterate through them with each instead of using first.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top