Groovy对xml的操作

Groovy对xml的操作

文中主要举两个例子:

  1. 查找一个xml文件的标签值
  2. 生成一个xml文件

示例xml:

def s = """
<!--   Copyright w3school.com.cn  -->
<root>
    <note>
        <to>George</to>
        <from>John</from>
        <heading>Reminder</heading>
        <body>Don't forget the meeting!</body>
    </note>
    <note>
        <to>George2</to>
        <from>John2</from>
        <heading>Reminder2</heading>
        <body>Don't forget the meeting2!</body>
    </note>
</root>
"""

查找一个xml文件的标签值

文中的例子可以查找到from标签值为John所在的note标签的to标签值是多少

def xml = new XmlSlurper().parseText(s)
def list = xml.depthFirst().findAll { note ->
    return note.from.text() == 'John' //这里从note开始点,查找出来的就是note
}.collect {
    it.to.text() //通过note获取下面的to节点的text
}
println list

创建一个xml

def sw = new StringWriter()
def x = new MarkupBuilder(sw)

x.root('isRoot':true) {  // 括号里面是键值对就是属性,如果是单个值的话,就是中间的value值
    note () { // 如果这个标签下有子标签,就用闭包的形式来声明
        to('George')
        from('John')
        heading('Reminder')
        body("Don't forget the meeting!")
    }
    note () {
        to('George2')
        from('John2')
        heading('Reminder2')
        body("Don't forget the meeting!2")
    }
}
println sw
发布了156 篇原创文章 · 获赞 19 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/qq_36929361/article/details/104247083