Groovy: Xml: how to read parsed XML text in a single loop

Have an xml string response that contains a child tag with a name <Name>, the response can contain one or more tags <Name>, as follows,

Case 1

Xml string = <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 the value 1 inside the first tag is <Name>obtained using the operator below

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

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

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

So how can I get value Akhilie: from the first tag in both cases using one operator

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

if I use this operator in case 2: then the error is like null

+4
source share
2

spread-. . , , xml .

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:

[Akhil, Akhil2] .

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

, :

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]
0

Source: https://habr.com/ru/post/1539869/


All Articles