Forum Discussion

vpachpute1's avatar
vpachpute1
Frequent Contributor
8 years ago

Groovy : XML Comparison: Dynamic XML Attributes are not ignored whie comparison.

Hi   I have one Groovy utility to compare current response with external response kept in xml file.   But while comparison, I am facing issue if parameter contains space. e.g. 1. If parameter is...
  • nmrao's avatar
    nmrao
    8 years ago

    vpachpute1,

     

    The data provided is not well-formed. Fixed a bit to make it well-formed.

     

    Here is the script:

     

    //assign xml string data for the below two statements, not assigned here to reduce the size of the script
    
    def expected = 
    def actual = 
    
    //Don't have to modify beyond this point
    
    //If required, add more ignore nodes or attributes(node: attribute format) in the below appropriately
    def ignoreNodes = ['purchase-date', 'expiry-date']
    def ignoreAttributes = ['subscription':'id']
    
    //Closure to update the xml with a fixed value REPLACED in place of dynamic value, so that comparison is done successfully
    def updateIgnoreElements = { data, fixedVal = 'REPLACED' ->
        def parsedData = new XmlSlurper().parseText(data)
        ignoreAttributes.each { k,v -> parsedData.'**'.findAll { it.name() == k}.collect{it.@"$v" = fixedVal} }
        ignoreNodes.each { element ->  parsedData.'**'.findAll { it.name() == element}.collect{it.replaceBody fixedVal} }
        groovy.xml.XmlUtil.serialize(parsedData) 
    }
    
    assert updateIgnoreElements(expected) == updateIgnoreElements(actual), 'Both are not matching'

    You can quickly try online demo and the same is available at github