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

时间:2010-08-09 12:10:06

标签: xml groovy xmlslurper

我正在使用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')

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

2 个答案:

答案 0 :(得分:7)

如果您在调用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>

答案 1 :(得分:4)

在需要之前,XMLSlurper不会对基础XML进行更改。当XMlSlurper进行所需的更改并输出结果时,您可以使用StreamingMarkupBuilder对其进行序列化。