Xml – Accessing child nodes of xml by name in Groovy while accessing parent node iteratively

groovysoapuixml

I have an XML like this:

<Envelope>
 <Node>
    <Status>1</Status>
    <Name1>John</Name1>
    <Name2>Smith</Name2>
 </Node>
 <Node>
    <Status>2</Status>
    <Name1>Jane</Name1>
    <Name2>Doe</Name2>
 </Node>
</Envelope>

I want to iterate through each node and if the value of Status is 1, use Name1 and if it is 2, use Name2.

Envelope = holder.getNodeValues("//ns2:NonProvisionedServers")
for(node in Envelope)
if(node.Status == 1)
{
    assert node.Name1 == "SomeFirstName"
}
if(node.Status == 2)
{
    assert node.Name2 == "SomeLastName"
}

I have done minimal Groovy scripting before. I've seen related posts but they only iterate through the child nodes, which I don't want to do since my parent node has a lot of child nodes, and I've a lot of parent nodes to go through. Any help would be appreciated.

Best Answer

You can do it this way:

def inx = '''<Envelope>
            |  <Node>
            |    <Status>1</Status>
            |    <Name1>John</Name1>
            |    <Name2>Smith</Name2>
            |  </Node>
            |  <Node>
            |    <Status>2</Status>
            |    <Name1>Jane</Name1>
            |    <Name2>Doe</Name2>
            |  </Node>
            |</Envelope>'''.stripMargin()

// Parse the XML
def xml = new XmlSlurper().parseText( inx )

// For every <Node> element in the XML
xml.Node.each { node ->

  // Print the child of the node called "Name" + Status
  println node."Name${node.Status}"
}

That prints:

John
Doe
Related Topic