Search code examples
javaxmlgrailsgroovyxml-parsing

XmlSlurper get node value clarification


XML file

<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

I want to read the value of the particular tag, I'm using XMLSlurper, below is my code

String sample ='to'
def person = new XmlSlurper().parse(new File("C:\\Desktop\\note.xml"))
println  person.to

for the above getting the answer = Tove.

But when I pass the tag name as string I'm not getting the value

String sample ='to'
def person = new XmlSlurper().parse(new File("C:\\Desktop\\note.xml"))
println  person.sample

getting empty string

Let me know how can I handle this?


Solution

  • Given your example you should use use your variable like this and let it be interpreted as a GString:

    String sample ='to'
    def person = new XmlSlurper().parse(new File("I:/Work/test.xml"))
    println  person."${sample}"