Forum Discussion

shubhimu's avatar
shubhimu
Contributor
6 years ago

Groovy Method to find out whether XML response has namespace in it or not

Hi,

 

Can anyone help me with the method to find out whether XML response has namespace in it or not. ?

 

Actually i want to achieve below:

If name space exist in response then i will set the name space and if it doesnt not exist then i will not set it.

I am using XMl holder for XMl parsing.

 

Thanks,

Himanshu

 

 

  • Hi,
    you would use XmlSlurper to parse xml.

    Hi,
    you would use XmlSlurper to parse xml. like below:
    // xmlResponse
    def rootNode = new XmlSlurper().parseText(xmlResponse)
    def gpathClass = rootNode.getClass().getSuperclass()
    def namespace = gpathClass.getDeclaredField("namespaceTagHints")
    namespace.setAccessible(true)
    def namespaceDeclaration = namespace.get(rootNode)
    log.info namespaceDeclaration

4 Replies

  • aaronpliu's avatar
    aaronpliu
    Frequent Contributor

    Hi,
    you would use XmlSlurper to parse xml.

    Hi,
    you would use XmlSlurper to parse xml. like below:
    // xmlResponse
    def rootNode = new XmlSlurper().parseText(xmlResponse)
    def gpathClass = rootNode.getClass().getSuperclass()
    def namespace = gpathClass.getDeclaredField("namespaceTagHints")
    namespace.setAccessible(true)
    def namespaceDeclaration = namespace.get(rootNode)
    log.info namespaceDeclaration

    • shubhimu's avatar
      shubhimu
      Contributor

      Hey aaronpliu Thanks for this!

       

      Can you please help me how i will go ahead and parse using XmlSlurper  when i have namespace in my response and if i dont have namsespace in response.?

       

      Because if i am using XmlSlurper  and printing the object of the same then its showing everything in a single form.

       

      Not able to see tag names of xml response.

       

      Sample response is like below in my case.

      TQA_AUTOMATION_20180724044736Req_201807240447362018-07-24T04:47:37.146 MDT2018-07-24T04:47:37.327 MDTtm1-yellow-rt104:yellow_fe:140001810OEAPI_USER_NAMEDIRECTAGREEMENT_TYPEDIRECTDEFAULT_OFFERCODE01DIRDISPLAY_LOGONBP__CNT_PHONEtool 

       

      I think i might need to convert it in to some xml format ?correct me if you any idea ?

       

      Thanks,

      Himanshu

      • shubhimu's avatar
        shubhimu
        Contributor

        After serialization i can see updated xml. Used below code

        def updatedXml= XmlUtil.serialize(rootNode)