tags:

views:

258

answers:

2

I know I can parse XML using Hpricot, but is it also possible to create files? All the tutorials I found only demonstrate parsing.

+4  A: 

Nah. Hpricot is only for parsing XML. It does not allow to build documents.

But you might want to take a look at Nokogiri, which allows you to parse and build documents.

Damien MATHIEU
+5  A: 

Jim Weirich's Builder is very easy to use. Here's an example from Enterprise Integration with Ruby by Maik Schmidt:

xml = '' 
doc = Builder::XmlMarkup.new(:target => xml, :indent => 2) 
doc.instruct!

doc.person(:name => 'Max', :surname => 'Mustermann') { |person| 
  person.address { |address| 
    address.street('Hauptstr. 42') 
    address.tag!('postal-code', '12345') 
    address.city('Musterstadt') 
  } 
  person.position(:longitude => 12.345, :latitude => 56.789) 
}

which produces:

<?xml version="1.0" encoding="UTF-8"?>
<person surname="Mustermann" name="Max">
  <address>
    <street>Hauptstr. 42</street>
    <postal-code>12345</postal-code>
    <city>Musterstadt</city>
  </address>
  <position longitude="12.345" latitude="56.789"/>
</person>
edavey