Ruby – Parse XML or Build XML

By polfilm,

  Filed under: Ruby
  Comments: None

To parse an XML string:

require 'xml'

xml = '<?xml version="1.0"?><root><child attr="value">text</child></root>'
root = XML::Parser.string(xml).parse.root
child = root.children.find { |node| node.name == "child" }
attr = child["attr"]

To build an XML document:

require 'xml'

xml = XML::Document.new
root = XML::Node.new("root")
child = XML::Node.new("child", "text")
child["attr"] = "value"
root << child
xml.to_s

Be the first to write a comment.

Your feedback

You must be logged in to post a comment.