如何使用Groovy在xml中插入/移动/删除节点?

fly*_*and 12 xml groovy

例如,我有以下xml文档:

def CAR_RECORDS = '''
    <records>
      <car name='HSV Maloo' make='Holden' year='2006'/>
      <car name='P50' make='Peel' year='1962'/>
      <car name='Royale' make='Bugatti' year='1931'/>
    </records>
'''
Run Code Online (Sandbox Code Playgroud)

我想把汽车"皇家"推到第一辆,并在汽车"HSV Maloo"之后插入一辆新车,结果将是:

'''
    <records>
      <car name='Royale' make='Bugatti' year='1931'/>
      <car name='HSV Maloo' make='Holden' year='2006'/>
      <car name='My New Car' make='Peel' year='1962'/>
      <car name='P50' make='Peel' year='1962'/>
    </records>
'''
Run Code Online (Sandbox Code Playgroud)

如何用Groovy做到这一点?欢迎评论.

Ted*_*eid 13

我沿着类似的路线前往danb,但在实际打印出生成的XML时遇到了问题.然后我意识到通过向root询问其所有"car"子项而返回的NodeList与通过询问root的子项获得的列表不同.尽管在这种情况下它们碰巧是相同的列表,但如果在根目录下有非"汽车"子项,它们并不总是如此.因此,重新记录从查询返回的汽车列表不会影响初始列表.

这是一个附加和重新排序的解决方案:

def CAR_RECORDS = '''
   <records>
     <car name='HSV Maloo' make='Holden' year='2006'/>
     <car name='P50' make='Peel' year='1962'/>
     <car name='Royale' make='Bugatti' year='1931'/>
   </records>
 '''

def carRecords = new XmlParser().parseText(CAR_RECORDS)

def cars = carRecords.children()
def royale = cars.find { it.@name == 'Royale' } 
cars.remove(royale)
cars.add(0, royale)
def newCar = new Node(carRecords, 'car', [name:'My New Car', make:'Peel', year:'1962'])

assert ["Royale", "HSV Maloo", "P50", "My New Car"] == carRecords.car*.@name

new XmlNodePrinter().print(carRecords)
Run Code Online (Sandbox Code Playgroud)

带有属性订购汽车的断言通过,XmlNodePrinter输出:

<records>
  <car year="1931" make="Bugatti" name="Royale"/>
  <car year="2006" make="Holden" name="HSV Maloo"/>
  <car year="1962" make="Peel" name="P50"/>
  <car name="My New Car" make="Peel" year="1962"/>
</records>
Run Code Online (Sandbox Code Playgroud)


fly*_*and 5

特德,也许你没注意到我想在汽车"HSV Maloo"'''之后插入一辆新车,所以我将你的代码修改为:

def newCar = new Node(null, 'car', [name:'My New Car', make:'Peel', year:'1962'])
cars.add(2, newCar)

new XmlNodePrinter().print(carRecords)
Run Code Online (Sandbox Code Playgroud)

现在,它适用于正确的订单!感谢danb&ted.

<records>
  <car year="1931" make="Bugatti" name="Royale"/>
  <car year="2006" make="Holden" name="HSV Maloo"/>
  <car name="My New Car" make="Peel" year="1962"/>
  <car year="1962" make="Peel" name="P50"/>
</records>
Run Code Online (Sandbox Code Playgroud)