Forum Discussion

jkrier's avatar
jkrier
Regular Contributor
9 years ago

Parsing XML file with Groovy script

I am trying to read in a naked xml file and parse it but for some reason XMLSlurper doesn't seem to be able to see child nodes. To make things easy I have created a groovy script with the xml inside of it so you don't need to bother with importing a file etc. this part I can do without error.

 

Here is an example of what I am trying to do

 

def testxml = '''
    <connStrings>
	<env>
		<envName>test</envName>
		<conn>
			<connName>wba</connName>
			<host>host01</host>
			<port>1500</port>
			<user>user01</user>
			<password>P@ssw0rd</password>
			<sid>sid01</sid>
		</conn>
	</env>
	</connStrings>
  '''

def myFile = new XmlSlurper().parseText(testxml)
m = myFile.connStrings.env.envName.toString()
log.info m
c = myFile.count("//connStrings/env/envName/conn/connName")
log.info c

When I run this it returns

 

  • Thu Sep 15 19:30:58 MDT 2016:INFO:
  • Thu Sep 15 19:30:58 MDT 2016:INFO:0

Any help anyone can give would be greatly appreciated.

  • jkrier

    Sorry about it, that was actually done quickly (could not test) for the change that you requested ( to loop thru all environments, and connection names)

    That was happening because, you provided all connection names, but some of them are not present in all environments.

    Handled now, please take the updated script from github.

  • nmrao's avatar
    nmrao
    Champion Level 3

    Here is the script:

     

    def testxml = '''<connStrings>
    <env>
      <envName>test</envName>
      <conn>
       <connName>wba</connName>
       <host>host01</host>
       <port>1500</port>
       <user>user01</user>
       <password>P@ssw0rd</password>
       <sid>sid01</sid>
      </conn>
    </env>
    </connStrings>'''
    
    def connStrings = new XmlSlurper().parseText(testxml)
    println "Environment name : ${connStrings.env.envName}"
    println "Connection name : ${connStrings.env.conn.connName}"
    ​

    • jkrier's avatar
      jkrier
      Regular Contributor

      Thank you for that. I also need to be able to count the <connName> node, in my actual file I have several of these. Do you know how that can be done?

      • nmrao's avatar
        nmrao
        Champion Level 3
        In that case please provide actual file, even above script may not work.