lakshman
lakshman

Reputation: 2741

how to get the xml under a specific node in groovy

I want to get the sub tree under <container> node as xml to a variable. I looked on GPathResult. but coudn't find any way to do that.

<shiporder orderid="889923"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="shiporder.xsd">
  <orderperson>John Smith</orderperson>
  <container>
  <item>
    <title>Empire Burlesque</title>
    <note>Special Edition</note>
    <quantity>1</quantity>
    <price>10.90</price>
  </item>
 </container>
</shiporder>

output xml should be

def xml= <item>
           <title>Empire Burlesque</title>
           <note>Special Edition</note>
           <quantity>1</quantity>
           <price>10.90</price>
         </item>

can someone point me to the right direction?

Upvotes: 0

Views: 675

Answers (1)

dmahapatro
dmahapatro

Reputation: 50245

Something like:

import groovy.xml.XmlUtil

def mainXml = 
'''
<shiporder orderid="889923"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="shiporder.xsd">
  <orderperson>John Smith</orderperson>
  <container>
  <item>
    <title>Empire Burlesque</title>
    <note>Special Edition</note>
    <quantity>1</quantity>
    <price>10.90</price>
  </item>
 </container>
</shiporder>
'''

def slurper = new XmlSlurper().parseText(mainXml)
XmlUtil.serialize(slurper.container.item)

Upvotes: 1

Related Questions