Skip to content

Instantly share code, notes, and snippets.

@samaaron
Created May 21, 2009 09:26
Show Gist options
  • Select an option

  • Save samaaron/115374 to your computer and use it in GitHub Desktop.

Select an option

Save samaaron/115374 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'libxml'
xml = <<END
<?xml version="1.0" encoding="UTF-8"?>
<location lat="54.444" long="23.232" />
END
#create parser for the xml string
parser = LibXML::XML::Parser.string(xml)
#parse the xml and turn it into a Document
doc = parser.parse
#this is where you can start to manipulate the data within the
#Document :-)
#for example, let's get all the location nodes and double their lat
#attribute
nodes = doc.find('/location')
nodes.each do |node|
lattitude = node["lat"]
double_lattitude = (lattitude.to_f * 2).to_s
node["lat"] = double_lattitude
end
#now we can see the fruits of our labours. LibXML also sports a
#save method which saves directly to a file see:
#http://libxml.rubyforge.org/rdoc/index.html
doc.to_s(:indent => true, :encoding => LibXML::XML::Encoding::UTF_8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment