简体   繁体   中英

Groovy Script to Parse XML values

Question

I need a groovy script to parse these ticket names and save them in user attributes

<?xml version="1.0" encoding="utf-8"?>
<root>
  <FTP FTPName="ftp.com.samplecompany.net" Login="CertUser" Pass="Password"></FTP>
  <Ticket name="Accept">
  </Ticket>
  <Ticket name="Afp">    
  </Ticket>
  <Ticket name="Exe">    
  </Ticket>
</root>

Current Code

def tickets = job.getDocuments()[0].getText().split(""></Ticket><Ticket name="") 
def len = tickets.size()

Solution

The following solution will add a new attribute user with the same value as name

import groovy.xml.StreamingMarkupBuilder

def xmlStr = '''
<root>
  <FTP FTPName="ftp.com.samplecompany.net" Login="CertUser" Pass="Password"></FTP>
  <Ticket name="Accept">
  </Ticket>
  <Ticket name="Afp">    
  </Ticket>
  <Ticket name="Exe">    
  </Ticket>
</root>
'''

def xml = new XmlParser().parseText(xmlStr)
println xml.Ticket['@name'].eachWithIndex { name, index ->
    xml.Ticket[index].@user = name
}


def outputBuilder = new StreamingMarkupBuilder()
def updatedXml = outputBuilder.bind{ mkp.yield xml }

println updatedXml

If you want to pull the XML to a file then write to the file you can modify the script accordingly

import groovy.xml.StreamingMarkupBuilder

def xmlFile = 'file.xml'
def xml = new XmlParser().parse(xmlFile)

println xml.Ticket['@name'].eachWithIndex { name, index ->
    xml.Ticket[index].@user = name
}

new XmlNodePrinter(new PrintWriter(new FileWriter(xmlFile))).print(xml)'

This will produce the following file

<root>
  <FTP FTPName="ftp.com.samplecompany.net" Login="CertUser" Pass="Password"/>
  <Ticket name="Accept" user="Accept"/>
  <Ticket name="Afp" user="Afp"/>
  <Ticket name="Exe" user="Exe"/>
</root>

Caution : It may remove the XML prolog

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