Parsing xml dict files

Hi,

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.

Something like the below but with actually building the hash on the fly?

require ‘rexml/document’

$doc = nil

File.open(“foo.xml”, “r”) do |aFile|
$doc = REXML::Document.new( aFile)
end

$doc.root.each_element("/dict/*") do |node|
puts node
end

This is plist format. Google “ruby plist reader”

http://plist.rubyforge.org/

Henry

cyber c. wrote in post #1064619:

A val1 B val2 C val3

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.

On Thu, Jun 14, 2012 at 7:53 PM, cyber c. [email protected] wrote:

A val1 B val2 C val3

08:55:20 Temp$ ./xml.rb
A → val1
B → val2
C → val3
08:55:36 Temp$ cat -n xml.rb
1 #!/opt/bin/ruby19
2
3 require ‘nokogiri’
4
5 dom = Nokogiri.XML <<XML
6
7
8 A
9 val1
10 B
11 val2
12 C
13 val3
14
15
16 XML
17
18 dom.xpath(‘//key’).each do |key|
19 printf “%s → %s\n”, key.text(),
key.at_xpath(‘following-sibling::string/text()’).text()
20 end

Cheers

robert

On 15 juin 2012, at 08:57, Robert K. wrote:

7  <dict>
8        <key>A</key>
9        <string>val1</string>

10 B
11 val2
12 C
13 val3
14

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.

require “plist”

xml = <<XML

A
val1
B
val2
C
val3

XML

puts Plist.parse_xml(xml)

On Fri, Jun 15, 2012 at 10:37 AM, Luc H. [email protected]
wrote:

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. :slight_smile: Also,
that way I could avoid installing a gem I otherwise do not need.

Cheers

robert