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.
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
···
-----Original Message-----
From: cyber c. [mailto:lists@ruby-forum.com]
Sent: Thursday, June 14, 2012 1:54 PM
To: ruby-talk ML
Subject: 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.
I want to match name with key and extract value from string. Please help
me.
You can use XPath again:
···
#-----------
require 'nokogiri'
xml = '
<dict>
<key>A</key>
<string>val1</string>
<key>B</key>
<string>val2</string>
<key>C</key>
<string>val3</string>
</dict>
'
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.
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 <dict>
8 <key>A</key>
9 <string>val1</string>
10 <key>B</key>
11 <string>val2</string>
12 <key>C</key>
13 <string>val3</string>
14 </dict>
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 Thu, Jun 14, 2012 at 7:53 PM, cyber c. <lists@ruby-forum.com> wrote:
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.
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
<dict>
<key>A</key>
<string>val1</string>
<key>B</key>
<string>val2</string>
<key>C</key>
<string>val3</string>
</dict>
XML
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
···
On Fri, Jun 15, 2012 at 10:37 AM, Luc Heinrich <luc@honk-honk.com> 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.