0

I am a newbee to Groovy, recently I need to count the complexity of a given XML data block.

I figure out a way to determine if the data block is XML formatted or not. But I am not sure how to count all the nodes of the given XML block.

Here is my code:

    def invoke(msg)        
    { 
    try {
       contentBody = msg.get("my.message");
       new XmlSlurper().parseText(contentBody);
       Trace.debug("XML is well formed, request body is "  + contentBody);
       return true;
    }

    catch (Exception e){
        Trace.error("Invalid xml, request body is " + contentBody);
            return false;
     }      
     }

Many thanks.

Cheers, Vincent

dhg
  • 64
  • 1
  • 7

2 Answers2

1

Have you tried the following?

new XmlSlurper().parseText(...).depthFirst().size()

sjtai
  • 480
  • 4
  • 11
1

So there are 2 things in the question

1) Checking if the xml is valid 2) Counting the number of nodes under a certain Node

Lets say you have a bad formed xml (Note : > is missed from tag

<note>
<to>Tove</to>
  <from
    <test>121</test>
     <testing>123</testing>
   </from>
 <heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note> 

Then the output is like

Mon Oct 01 08:34:54 IST 2018: ERROR: Invalid XML
Mon Oct 01 08:34:54 IST 2018: ERROR: org.apache.xmlbeans.XmlException: error: Unexpected character encountered (lex state 10): '<'

So here is the code

 def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)

 try
{
 def xmlHolder = groovyUtils.getXmlHolder("RequestName#Request")
 def countofRoot = xmlHolder.getDomNodes("//*").size()
 def countofbelowNodes = xmlHolder.getDomNodes("//*:from/*").size()

  log.info "size of XML is " + countofRoot
  log.info "size of XML is " + countofbelowNodes

   }
  catch(Exception e)
  {
   log.error "Invalid XML"
    log.error e
   }

When the XML is correct. It gives the below output

enter image description here

Please note if you give wrong xpath then exception can come due to that also. So its not necessary that its an Invalid XML. But the e i.e exception detail will help you in knowing the problem

i feel easy to use xmlHolder then XMLParser/XMLSlurper

Gaurav Khurana
  • 3,423
  • 2
  • 29
  • 38