首页 > 解决方案 > Extracting an xml value in Groovy

问题描述

I have this code

String dbresponse = '''
 <rows>
  <row>
    <file_data>One</file_data>
    <time_inserted>2019-01-30T10:29:20.543</time_inserted>
  </row>
  <row>
    <file_data>two</file_data>
    <time_inserted>2019-01-30T10:29:20.547</time_inserted>
  </row>
  <row>
    <file_data>three</file_data>
    <time_inserted>2019-01-30T10:29:20.550</time_inserted>
  </row>
  <row>
    <file_data>four</file_data>
    <time_inserted>2019-01-30T10:29:20.550</time_inserted>
  </row>
  <row>
    <file_data>five</file_data>
    <time_inserted>2019-01-30T10:29:20.553</time_inserted>
  </row>
 </rows>    
'''

def response = new XmlSlurper().parseText(dbresponse)
def data = response.rows.row[1].file_data
print data

I have two questions:

1] With the above code why am I not getting the response of: two ? 2] How do I iterate through the entire xml doc to get this response: one two three four five

Thanks

标签: groovy

解决方案


Here is how it works:

def rows = new XmlSlurper().parseText(dbresponse)
print (rows.row[1])
print (rows.row[1].file_data)

The identifier, rows, gives a handle on the object returned when parsing dbresponse (<rows> in this case). I named it rows since this is the convention slurp'ers use; it doesn't have to be.


推荐阅读