XmlSlurper 获取节点值澄清

XmlSlurper get node value clarification

XML 文件

<?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>

我想读取特定标签的值,我正在使用 XMLSlurper,下面是我的代码

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

以上得到答案=Tove.

但是当我将标签名称作为字符串传递时,我没有得到值

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

获取空字符串

让我知道我该如何处理?

鉴于你的例子,你应该像这样使用你的变量并让它被解释为 GString:

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