加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

怎样使用Groovy给XML增加特性

发布时间:2020-12-14 16:48:10 所属栏目:大数据 来源:网络整理
导读:怎样使用Groovy给XML增加特性? 问: 在Groovy中,我需要增加一个特性(attribute)到XML的根元素。我想使用 XmlSlurper。该怎样做?增加元素是很简单。 答: 在Groovy Console 运行以下代码,结果良好。 import?groovy.xml.StreamingMarkupBuilder//?the?ori

怎样使用Groovy给XML增加特性?


问:

在Groovy中,我需要增加一个特性(attribute)到XML的根元素。我想使用 XmlSlurper。该怎样做?增加元素是很简单。

答:

在Groovy Console 运行以下代码,结果良好。

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

增加一个特性与读一个特性是一样的:

import?groovy.xml.StreamingMarkupBuilder

def?input?=?'''
<thing>
????<more>
????</more>
</thing>'''

def?root?=?new?XmlSlurper().parseText(input)

root.@stuff?=?'new'

def?outputBuilder?=?new?StreamingMarkupBuilder()
String?result?=?outputBuilder.bind{?mkp.yield?root?}

println?result

将生成:

<thing?stuff='new'><more></more></thing>

来源:?<http://stackoverflow.com/questions/7795494/how-to-add-xml-attribute-using-groovy>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读