# To generate xml, you must create a rexml: document object instance.
Require "Rexml/document"
File = file. New ("test. xml", "W + ")# Create an XML file and write the following content .
Doc = Rexml: Document. New # Create XML content
# Add a node for the rexml document
Element = Doc. Add_element ('Book', {'name' => 'gramming Ruby ', 'author' => 'Joe chu '})
Chapter1 = element. Add_element ( 'Chapter ', {'title' => 'Chapter 1 '})
Chapter2 = element. Add_element ('Chapter ', {'title' => 'Chapter 2 '})
# Add content to a node
Chapter1. Add_text "Chapter 1 content"
Chapter2. Add_text "Chapter 2 content"
Doc. Write
File. Puts Doc. Write
# Parsing XML
Require "Rexml/document"
Xml_doc = % {
<Book name = 'Programming Ruby 'author = 'Joe chu'>
<Chapter Title = 'Chapter 1 '>
Chapter 1 content
</Chapter>
<Chapter Title = 'Chapter 2'>
Chapter 2 Content
</Chapter>
</Book>
}
# Create a rexml: Document instance and parse the xml_doc file. We can use the last file 'xml _ doc', or last file test. xml
#~ Doc = rexml: Document. New (Xml_doc)
Doc = rexml: Document. New (File. Open ("test. xml "))
Puts Doc. Root. Name # Output and node name
Puts Doc. Root. attributes ['name'] # Output the name attribute value of the Root Node
Puts Doc. Root. attributes ['autor'] # Output the author attribute value of the Root Node
Chapter1 = Doc. Root. elements [1] # Subnodes in the output Node
Puts chapter1.attributes ['title'] # Output the title attribute value of the first node
Puts chapter1.text # Output the text contained in the First Node