Ruby 手册 | 28 - XML 和 YAML 操作

278 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第28天,点击查看活动详情

一、操作 XML

XML 既可扩展标记语言,是一种非常流行的标记语言,常用作配置文件。Ruby 中对 XML 的操作提供了良好的支持,Ruby 中的 REXML 库是常用的操作 XML 文件的标准库。

比如 Maven 的配置文件 pom.xml 文件的格式如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.9</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.spring.selenium</groupId>
    <artifactId>spring-selenium</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

创建 XML

REXML 中提供了创建 XML 文档的方法,既实例化一个 REXML::Document 对象。

x = REXML::Document.new
require 'rexml/document'

# 创建 xml 文件实例
xml_file = REXML::Document.new

# 给 xml 文件添加节点
ele = xml_file.add_element('book', {'name' => 'Ruby 编程', 'author' => 'Thomas'})
ch1 = ele.add_element('chapter', {'title' => 'Chapter 1'})
ch2 = ele.add_element('chapter', {'title' => 'Chapter 2'})

# 为节点添加包含内容
ch1.add_text "Chapter 1 Content"
ch2.add_text "Chapter 2 Content"

xml_file.write

执行上述代码,输出结果如下:

<book author='Thomas' name='Ruby 编程'>
    <chapter title='Chapter 1'>Chapter 1 Content</chapter>
    <chapter title='Chapter 2'>Chapter 2 Content</chapter>
</book>

通过上述代码,首先创建了一个 XML 文件,之后通过 add_element 方法在 XML 文件中添加一个个的节点,并通过 add_text 方法往节点中添加内容。

解析 XML

REXML::Document 对象中还包含了解析 XML 文件的方法

  • root:输出根节点的节点名
  • root.attributes['attrname']:根据属性名输出根节点的属性值
  • elements[index]:根据索引获取子节点,索引从 1 开始
  • text:获取节点内容
# 获取根节点
root_node = xml_file.root
# 输出根节点名
puts root_node.name

# 输出根节点的属性
puts root_node.attributes
puts root_node.attributes['author']

# 输出第二层节点
second_node = root_node.elements[1]
puts second_node.attributes['title']
puts second_node.text

执行上述代码,输出结果如下:

book
{"name"=>name='Ruby 编程', "author"=>author='Thomas'}
Thomas
Chapter 1
Chapter 1 Content

二、操作 YAML

除了 XML 之外,YAML 也是常用的配置文件格式,且 YAML 比 XML 阅读性更强,许多 Ruby 应用都是用 YAML 格式文件来保存配置,使用 YAML 库就可以很方便的将 Ruby 对象转换成 YAML 格式。

YAML 格式文件通过缩进来表示层次结构,列表可以使用 - 来表示,数组可以使用 [],Hash 则可以使用 {} 来表示。

YAML 类的常用方法如下:

  • YAML.dump(obj):将对象转化成 YAML 格式字符串
  • YAML.load(str):解析 YAML 格式字符串,转换为 Ruby 对象
  • YAML.load_file(filename):直接读取 YAML 格式配置文件,转换为 Ruby 对象。
require 'yaml'

str = "Hello Ruby"
age = 20
langs = ["Ruby", "Python", "Scala", "Elixir"]
info = ["Ruby" => "Rails", "Elixir" => "Phoenix"]

# 转为 Ruby 对象
puts str.to_yaml
puts age.to_yaml
puts langs.to_yaml
puts info.to_yaml

执行上述代码,输出结果如下:

--- Hello Ruby
--- 20
---
- Ruby
- Python
- Scala
- Elixir
---
- Ruby: Rails
  Elixir: Phoenix

YAML 格式文件的创建和解析

require 'yaml'

data = []

data << {:name => "tony", :age => 22}
data << {:name => "Bob", :age => 23}
data << {:name => "charlie", :age => 24}

# 写入 YAML 文件
File.open("data.yml", 'w') do |file|
  YAML.dump(data,file)
end

# 读取 YAML 文件
yaml_data = YAML.load_file('data.yml')
puts yaml_data.size

yaml_data.each do |i|
  puts "name: #{i[:name]}, age: #{i[:age]}"
end

执行上述的代码,输出结果如下:

3
name: tony, age: 22
name: Bob, age: 23
name: charlie, age: 24

并且可以看到,同级目录下会多处一个 data.yml 文件,这就是 YAML 类创建的文件。