gpt4 book ai didi

xml - Groovy 删除 XMLSlurper 中的标签,replaceNode {} 什么都不做

转载 作者:数据小太阳 更新时间:2023-10-29 02:16:19 31 4
gpt4 key购买 nike

我正在使用 XMLSlurper (groovy 1.7.4) 解析一些 XML,我需要删除一个标签(而不是让它为空!)。这是说明它的代码示例:

import groovy.xml.StreamingMarkupBuilder

def CAR_RECORDS = '''
<records>
<car name='HSV Maloo' make='Holden' year='2006'>
<country>Australia</country>
<record type='speed'>Production Pickup Truck with speed of 271kph</record>
</car>
<car name='P50' make='Peel' year='1962'>
<country>Isle of Man</country>
<record type='size'>Smallest Street-Legal Car at 99cm wide and 59 kg in weight</record>
</car>
<car name='Royale' make='Bugatti' year='1931'>
<country>France</country>
<record type='price'>Most Valuable Car at $15 million</record>
</car>
</records>
'''

def records = new XmlSlurper().parseText(CAR_RECORDS)
def allRecords = records.car
assert 3 == allRecords.size()

def firstRecord = records.car[0]
assert 'car' == firstRecord.name()
println 'country before: ' + firstRecord.'country'.text()
firstRecord.'country'.replaceNode {}

println 'country after: ' + firstRecord.'country'.text()

这打印

country before: Australia
country after: Australia

在 XMLSlurper 中,没有 firstRecord.remove('country')

我真的很困惑。这是一件显而易见的事情...

最佳答案

如果您在调用 replaceNode 之后从 Slurper 打印出 XML:

import groovy.xml.XmlUtil

// ... your code here, followed by: ...

println XmlUtil.serialize(new StreamingMarkupBuilder().bind {
mkp.yield records
} )

国家节点好像没了:

<?xml version="1.0" encoding="UTF-8"?>
<records>
<car name="HSV Maloo" year="2006" make="Holden">
<record type="speed">Production Pickup Truck with speed of 271kph</record>
</car>
<car name="P50" year="1962" make="Peel">
<country>Isle of Man</country>
<record type="size">Smallest Street-Legal Car at 99cm wide and 59 kg in weight</record>
</car>
<car name="Royale" year="1931" make="Bugatti">
<country>France</country>
<record type="price">Most Valuable Car at $15 million</record>
</car>
</records>

关于xml - Groovy 删除 XMLSlurper 中的标签,replaceNode {} 什么都不做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3439837/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com