2010-08-09 62 views
3

我用XMLSlurper(groovy 1.7.4)解析了一些XML,我需要刪除一個標記(不要讓它爲空!)。下面是對其進行說明的代碼示例:Groovy刪除XMLSlurper中的標記,replaceNode {}什麼都不做

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( '國家')

我真的很困惑。這是這樣做的一個明顯的事情......

回答

7

如果後打印出從Slurper的XML您的來電,雖然replaceNode:

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

XMLSlurper在需要之前不會更改底層XML。當XMlSlurper將進行所需的更改並輸出結果時,您可以使用StreamingMarkupBuilder將其序列化。