简体   繁体   中英

Read XML tag values based on other tags using Groovy Script

I'm new to Groovy scripting and I need some help in fetching tag values based on different tag. Below is the response I'm receiving from my application through SOAP.

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soap:Body>
  <DataResponse xmlns="http://eh.dummy.com">
     <onlinePartyData xmlns="">
        <tabs xmlns="http://eh.dummy.com">
           <tabs_InnerSet>
              <Tabs_InnerSet_TupleType>
                 <tab>
                    <DISPLAY_TEXT>DESCRIPTION 1</DISPLAY_TEXT>
                    <qsets>
                       <qsets_InnerSet>
                          <Qsets_InnerSet_TupleType>
                             <qset>
                                <SET_CD>QS1</SET_CD>
                                <VISIBLE>true</VISIBLE>
                             </qset>
                          </Qsets_InnerSet_TupleType>
                          <Qsets_InnerSet_TupleType>
                             <qset>
                                <SET_CD>QS2</SET_CD>
                                <VISIBLE>true</VISIBLE>
                             </qset>
                             <qset>
                                <SET_CD>QS3</SET_CD>
                                <VISIBLE>false</VISIBLE>
                             </qset>
                          </Qsets_InnerSet_TupleType>

                       </qsets_InnerSet>
                    </qsets>
                 </tab>
              </Tabs_InnerSet_TupleType>
           </tabs_InnerSet>
        </tabs>
     </onlinePartyData>
  </DataResponse>
</soap:Body>
</soap:Envelope>

I need SET_CD tag values to be concatenated if VISIBLE node is true. In this example, I need output of my groovy script as QS1, QS2. How can I achieve this?

Thanks!!

Here is the script that queries the xml where VISIBLE = true and fetches the SET_CD values and joins them.

Note that the xml provided in the question is not well-formed. Fixed that while testing.

Groovy Script

//Pass the xml string to parseText method
def parsedXml = new XmlSlurper().parseText(xml)
def result = parsedXml.'**'.findAll {it.VISIBLE == true}.SET_CD.join(',')
println result
assert result instanceof String 

If you want to try this quickly online Demo

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