I know that i can use “Nokogiri” to parse xml files and search for
results.
How do we deal with xml dict files where you have a [key,string] pairs
associated.
Sample file
<? xml version="1.0" enc..... ?>
A
val1
B
val2
C
val3
I want to match name with key and extract value from string. Please help
me.
I want to match name with key and extract value from string. Please help
me.
You can use XPath again:
#-----------
require ‘nokogiri’
xml = ’
A
val1
B
val2
C
val3
’
document = Nokogiri::XML.parse xml
def get_string doc, key
doc.xpath("//key[text()=’#{key}’]/following-sibling::*[1]/text()").text
end
puts get_string(document, ‘B’) #-----------
By the way: I’m no XML expert, but relying on the order of the elements
seems a rather “ugly” solution to me. I’d rather wrap the key string
pairs in “entry” elements or so.
This furiously looks like a property list which I will assume is what
you want to parse, in which case don’t even bother using Nokogiri and
simply use the plist gem.
This furiously looks like a property list which I will assume is what you want
to parse, in which case don’t even bother using Nokogiri and simply use the plist
gem.
I liked to use that opportunity to train my XPath skills. Also,
that way I could avoid installing a gem I otherwise do not need.
Cheers
robert
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.