开发者

Groovy delete a tag in a XMLSlurper, replaceNode {} does nothing

开发者 https://www.devze.com 2023-01-11 05:50 出处:网络
I am parsing some XML with XMLSlurper (groovy 1.7.4) and I need to delete a tag (not make it empty!). Here is a code sample illustrating it:

I am parsing some XML with XMLSlurper (groovy 1.7.4) and I need to delete a tag (not make it empty!). Here is a code sample illustrating it:

import groovy.xml.Str开发者_高级运维eamingMarkupBuilder

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()

This prints

country before: Australia
country after: Australia

In XMLSlurper, there is no firstRecord.remove('country')

I'm really puzzled. This is such an obvious thing to do...


If you print out the XML from the Slurper after your call to replaceNode though:

import groovy.xml.XmlUtil

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

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

The country node seems to be gone:

<?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>


XMLSlurper does not make changes to the underlying XML until required. You can serialize it using StreamingMarkupBuilder when XMlSlurper will make the required changes and output the results.

0

精彩评论

暂无评论...
验证码 换一张
取 消