2010-08-09 4 views
3

일부 XML을 XMLSlurper (groovy 1.7.4)로 구문 분석 중이므로 태그를 삭제해야합니다 (비워 두지 마십시오!). 여기를 설명하는 코드 샘플은 다음과 같습니다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() 

이 XMLSlurper에서

country before: Australia 
country after: Australia 

을 인쇄, 난 정말 의아해 해요 더 firstRecord.remove ('국가')

가 없습니다. 후에는 Slurper에서 XML을 인쇄 할 경우이 할 수있는 그런 뻔한 일이다 ...

답변

7

는 전화하지만 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를 사용하여 직렬화 할 수 있습니다.