简体   繁体   中英

Extract string from XML using Groovy

我有一个XML节点,我想检查特定的字符串,例如<name.firstname>john</name.firstname>因此我想遍历整个xml文件并查找所有名字,然后获取值为john的值。谁能帮我这个

Suppose the XML was formatted like this:

<results>
 <person>
  <name.firstname>john</name.firstname>
 </person>
 <person>
  <name.firstname>mary</name.firstname>
 </person>
</results>

With Groovy and XmlSlurper you can parse out the first name element with following code:

def results = new XmlSlurper().parseText(text) 
def people = results.person // list of person elements of type NodeChildren
people.each{ person ->
 String name = person."name.firstname".text()
 println name
}

You need to quote the "name.firstname" element since the "." would be confused with the XPath notation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM