簡體   English   中英

如何使用Groovy在xml中插入/移動/刪除節點?

[英]How to insert/move/delete nodes in xml with 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>
'''

我想把汽車“皇家”推到第一輛,並在汽車“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>
'''

如何用Groovy做到這一點? 歡迎評論。

我沿着類似的路線前往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)

帶有屬性訂購汽車的斷言通過,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>

特德,也許你沒注意到我想在汽車“HSV Maloo”'''之后插入一輛新車,所以我將你的代碼修改為:

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

new XmlNodePrinter().print(carRecords)

現在,它適用於正確的訂單! 感謝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>

<手波> 這些不是你尋求的密碼 </ hand-wave>

Node root = new XmlParser().parseText(CAR_RECORDS)
NodeList carNodes = root.car
Node royale = carNodes[2]
carNodes.remove(royale)
carNodes.add(0, royale)
carNodes.add(2, new Node(root, 'car', [name:'My New Card', make:'Peel', year:'1962']))

我不知道是否有更聰明的方法來創建新節點......但這對我有用。

編輯:呃...謝謝你們...我懶得打印carNodes,當我測試這個而不是根... yikes。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM