如何使用Groovy添加XML属性? [英] How to add XML attribute using Groovy?

查看:202
本文介绍了如何使用Groovy添加XML属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Groovy的XML片段的根元素中添加@属性。我想要使​​用 XmlSlurper 。怎么做?添加元素很简单。

I need to add @ attribute to the root element of XML fragment in Groovy. I want to use XmlSlurper. How to do it? Adding elements is easy.

推荐答案

在Groovy控制台中运行它以验证它是否正常运行

Run this in the Groovy console to verify that it works

import groovy.xml.StreamingMarkupBuilder

// the original XML
def input = "<foo><bar></bar></foo>"

// add attributeName="attributeValue" to the root
def root = new XmlSlurper().parseText(input)
root.@attributeName = 'attributeValue'

// get the modified XML and check that it worked
def outputBuilder = new StreamingMarkupBuilder()
String updatedXml = outputBuilder.bind{ mkp.yield root }

assert "<foo attributeName='attributeValue'><bar></bar></foo>" == updatedXml

这篇关于如何使用Groovy添加XML属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆