Antony Prince
Antony Prince

Reputation: 319

Groovy:Xml: How to read parsed xml string's text within a single loop

Have an xml string response which contain a child tag named <Name> ,the response may contain one or more <Name> tags as given below,

Case 1

String Xml =<School> <Student> <Name>Akhil</Name> <Name>Nikhil</Name> <Name>Kiran</Name> </Student> <School>

Case 2 String Xml =<School> <Student> <Name>Akhil</Name> </Student> <School>

String parsedXml =  new XmlParser(false,false).parseText(Xml)

in case 1 value inside the first <Name> tag is obtained by using below statement

Case 1
     String name = parsedXml.Student.Name[0].text()

in case 2 value inside the <Name> tag is obtained by using below statement

Case 2
     String name = parsedXml.Student.Name.text()

So how can i get value Akhil ie: from first tag in both case by using one statement

String name = parsedXml.Student.Name[0].text()

if i use this statement in case 2: then an error as null

Upvotes: 4

Views: 1147

Answers (2)

Opal
Opal

Reputation: 84756

This way You'll always get a list:

def xml1 = '''<School>
                    <Student>
                        <Name>Akhil</Name>
                        <Name>Nikhil</Name>
                        <Name>Kiran</Name>
                   </Student>
             </School>'''

def xml2 = '''<School>
                    <Student>
                        <Name>Akhil</Name>
                    </Student>
             </School>'''
def xml1p = new XmlParser(false,false).parseText(xml1)
def xml2p = new XmlParser(false,false).parseText(xml2)

println xml1p.Student.Name*.text().first() //or [0]
println xml2p.Student.Name*.text().first() //or [0]

Upvotes: 0

Seagull
Seagull

Reputation: 13859

You can use spread-dot operator. It will access ALL child nodes with given name. It will return you a list, wich you can then flatten, if you have unregular xml structure with both tag cases inside.

String xml ="""<School>
  <Student>
    <Name>Akhil</Name>
    <Name>Nikhil</Name>
    <Name>Kiran</Name>
  </Student>
  <Student>
    <Name>Akhil2</Name>
  </Student>
</School>"""

def res = new XmlParser().parseText(xml).Student*.Name.flatten()*.text()
println(res) //[Akhil, Nikhil, Kiran, Akhil2]

EDIT:

This line will give you [Akhil, Akhil2] as output.

new XmlParser().parseText(xml).Student*.Name.collect { it[0] }*.text()

Upvotes: 2

Related Questions