Isha
Isha

Reputation: 95

Getting the value of child node in xml using groovy

How do I parse the value of Profile in the below xml using groovy?

<Books>
        <Book>
                <Profile>Science</Profile>
                <Extension>.png</Extension>
                <Length>1920</Length>
                <Width>1080</Width>
        </Book>
        <Book>
                <Profile>English</Profile>
                <Extension>.png</Extension>
                <Length>640</Length>
                <Width>460</Width>
        </Book> 
</Books>

I have tried:

def bookxml = new XmlSlurper().parseText(bookText)
def profile = bookxml.Book.findAll { it.Profile } 

but this is not working as expected.

Upvotes: 1

Views: 8964

Answers (1)

Opal
Opal

Reputation: 84874

It should work well - if the syntax is corrected parseText instead of parsexml - all the profiles are found.

Catch the sample:

def bookXml = '''<Books>
        <Book>
                <Profile>Science</Profile>
                <Extension>.png</Extension>
                <Length>1920</Length>
                <Width>1080</Width>
        </Book>
        <Book>
                <Profile>English</Profile>
                <Extension>.png</Extension>
                <Length>640</Length>
                <Width>460</Width>
        </Book> 
</Books>'''

def bookxml = new XmlSlurper().parseText(bookXml)
bookxml.Book.findAll { it.Profile }.each { println it.Profile.text() }

Upvotes: 1

Related Questions