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>
def tickets = job.getDocuments()[0].getText().split(""></Ticket><Ticket name="")
def len = tickets.size()
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.