1

I have the following xml file:

/my_file.xml

<?xml version="1.0" encoding="utf-8" ?>
<words>
  <w>my_word</w>
  <w>second_word</w>
</words>

How can I do the following using Ruby:

  1. Load
  2. Parse
  3. Transform an xml file to an instance of a ruby array:
words = ["my_word","second_word"]

1 Answer 1

3

With the Nokogiri gem...

require 'rubygems'
require 'nokogiri'

xml = '<?xml version="1.0" encoding="utf-8" ?>
<words>
<w>my_word</w>
<w>second_word</w>
</words>'

doc = Nokogiri::XML(xml)
words = doc.xpath("//w").map {|x| x.text}
Sign up to request clarification or add additional context in comments.

2 Comments

Except that XPath will return the Nokogiri text nodes instead of the text itself, try this instead doc.xpath("//w").map {|x| x.text}.
In Ruby 1.9 it may be even shorter: oc.xpath("//w").map(&:text)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.