Reputation: 53
XML Data:
<configs>
<config>
<name>XP</name>
<browser>IE</browser>
<browser>FF</browser>
<browser>Chrome</browser>
</config>
</configs>
I'm new to Ruby, Nokogiri, and programming in general. I'm trying to write a QA tool to help with automation.
Ruby code:
doc = Nokogiri::XML(open("configs.xml"))
configs = doc.xpath("//configs/config").map do |i|
{'name' => i.xpath('name').to_s, 'browsers' => i.xpath('browser').to_s}
end
configs.each do |i|
puts i['name']
puts i['browsers']
end
This does what I want it to, it returns the data, but includes the XML tags. Is there a way to strip them that I'm just not finding?
Upvotes: 3
Views: 201
Reputation: 160181
Use .text
to get text node data:
:name => i.xpath('name').text
.to_s
is the string representation of an XML node, which is more than you're looking for.
However, the rest of your code is a bit broken if you're expecting individual browser entries.
As-is it'll smash the text data together into a single blob. Instead join them together, etc, for example:
configs = doc.xpath("//configs/config").collect do |cfg|
browsers = cfg.xpath('browser').collect { |b| b.text }.join(', ')
{ name: cfg.xpath('name').text, browsers: browsers }
end
configs.each do |i|
puts i[:name]
puts i[:browsers]
end
You may want a blob of "IEFFChrome"
, in which case never mind.
Upvotes: 7