XmlSlurper.appendNode不会更改大小

时间:2011-06-06 16:45:34

标签: xml groovy xmlslurper

我使用XmlSlurper处理XML。它工作正常,直到我更新它。 appendNode不反映大小。

如何在结构更新后使用XmlSlurper?

XML定义:

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)
records.appendNode( { car(make:'BMW') } ) 
assert 4 == records.car.size() //fails!!! size == 3

打印包括宝马汽车在内的XML

def xmlOut = new groovy.xml.StreamingMarkupBuilder()    
def temp = xmlOut.bind{ 
        mkp.yield records   
} 
​println temp​

2 个答案:

答案 0 :(得分:5)

您可以使用XmlSlurper再次阅读新创建的结构。

...

records = new XmlSlurper().parseText(temp as String)
assert 4 == records.car.size()

答案 1 :(得分:0)

试试这个

records = records.appendNode( { car(make:'BMW') } ) 

更新:实际上这段代码没有编译(请参阅注释),所以我稍后会发布自己的解决方法结果。

在某些项目中我使用了模板字符串,如:

static final String template = '<row><someList></someList></row>'

你可以像这样添加节点(lang Groovy):

    def row = new XmlSlurper().parseText(template);
    row.someList.appendNode(){
      ListElement(){
        field1('A')
        field2('B')
        field3('B')
      }
    }