Ruby ---- XML creation and parsing

Source: Internet
Author: User

# 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

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.