Groovy - 修改 XML
在 Groovy 中,我们可以轻松修改 XML 内容。在本章中,我们将通过以下步骤来实现。
加载现有的 XML 文档
使用 XmlSlurper 遍历 XML 文档
修改 XML 文档中的元素和属性
将修改后的文档序列化为字符串或文件
加载并解析现有的 XML 文档
使用 XmlSlurper,我们可以在应用中加载 XML 文档。
def xmlMovies = '''
<movies>
<movie title = 'Enemy Behind'>
<type>War, Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>PG</stars>
<description>10</description>
</movie>
<movie title = 'Transformers'>
<type>Anime, Science Fiction</type>
<format>DVD</format>
<year>1989</year>
<rating>R</rating>
<stars>R</stars>
<description>8</description>
</movie>
</movies>
'''
// 将 xml 解析为 movies 对象
def movies = new XmlSlurper().parseText(xmlMovies)
对元素和属性的修改
现在遍历 XML 结构并修改元素和属性。
// 修改第一部电影的标题
movies.movie[0].@title = 'GodZilla Plus One'
// 为第一部电影添加一个新元素
movies.movie[0].appendNode { edition 'I' }
// 从第二部电影中移除一个元素
movies.movie[1].year.replaceNode {}
常用方法
replaceNode() − 要替换现有节点,可以在 closure 中使用 replaceNode() 并提供新节点内容。这对于替换元素的名称、属性或内容非常有用。
直接赋值 − 对于简单的基于文本的更改,可以直接赋值。
appendNode 用于向 XML 文档添加新节点。
@attributeName=value 用于更新现有属性的值。
replaceNode − 要替换或移除 XML 文档中的节点,此方法非常有用。可以传递空 closure 来移除节点,或传递新节点来替换现有节点。
序列化更新后的 XML
完成更改后,可以将 XML 序列化为字符串或文件。
import groovy.xml.XmlUtil def updatedXml = XmlUtil.serialize(movies) println updatedXml
完整示例 - 修改 XML
Example.groovy
import groovy.xml.XmlUtil
def xmlMovies = '''
<movies>
<movie title = 'Enemy Behind'>
<type>War, Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>PG</stars>
<description>10</description>
</movie>
<movie title = 'Transformers'>
<type>Anime, Science Fiction</type>
<format>DVD</format>
<year>1989</year>
<rating>R</rating>
<stars>R</stars>
<description>8</description>
</movie>
</movies>
'''
// 将 xml 解析为 movies 对象
def movies = new XmlSlurper().parseText(xmlMovies)
// 修改第一个 movie 的 title
movies.movie[0].@title = 'GodZilla Plus One'
// 为第一个 movie 添加一个新元素
movies.movie[0].appendNode { edition 'I' }
// 从第二个 movie 中移除一个元素
movies.movie[1].year.replaceNode {}
def updatedXml = XmlUtil.serialize(movies)
println updatedXml
输出
运行上述程序时,将得到以下结果。
<?xml version="1.0" encoding="UTF-8"?><movies>
<movie title="GodZilla Plus One">
<type>War, Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>PG</stars>
<description>10</description>
<edition>I</edition>
</movie>
<movie title="Transformers">
<type>Anime, Science Fiction</type>
<format>DVD</format>
<rating>R</rating>
<stars>R</stars>
<description>8</description>
</movie>
</movies>