groovy 我正在尝试加载一个xml文件,然后从该文件中删除一些项,然后将其写回该文件

xdyibdwo  于 2022-11-01  发布在  其他
关注(0)|答案(2)|浏览(220)

我的代码到现在为止:

import groovy.xml.XmlParser
import groovy.xml.XmlNodePrinter

// def xmlfile = readFile "./report.xunit"

String fileContents = new File('report.xml').getText('UTF-8')
    println('XML File is  - '+fileContents)
def xml = new XmlParser()

def testSuites = xml.parseText(fileContents)
    println('xml articles are  '+testSuites)

testSuites.findAll { it.testcase.'@file'.text().contains('.py') }.each { articles.remove(it) }
def xmlFile = "report.xunit"
new XmlNodePrinter(new PrintWriter(new FileWriter(xmlFile))).print(xml)

XML文件内容看起来像这样:

<?xml version="1.0" encoding="UTF-8"?><testsuite errors="0" failures="0" name="TestResults" prefix="my_workspace" skips="0" tests="6" time="28.0"><testcase classname="extra" file="sample.py" name="sample" time="0.0"/><testcase classname="TestItem1" file="myfolder/TestScript.xml" name="TC001" exectime="14.0"/><testcase classname="TestItem1" file="myfolder/TestScript.py" name="TC001_data" exectime="0.0"/><testcase classname="TestItem1" file="myfolder/TestScript.xml" name="TC002" exectime="14.0"/><testcase classname="TestItem1" file="myfolder/TestScript.py" name="TC002_data" exectime="0.0"/><testcase classname="extra" file="final_out.py" name="final_out" time="0.0"/></testsuite>

而我的输出应该是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<testsuite errors="0" failures="0" name="TestResults" prefix="my_workspace" skips="0" tests="2" time="28.0">
<testcase classname="TestItem1" file="myfolder/TestScript.xml" name="TC001" exectime="14.0"/>
<testcase classname="TestItem1" file="myfolder/TestScript.xml" name="TC002" exectime="14.0"/>
</testsuite>

我将在jenkins中运行相同的命令,此时我将使用readFile函数

idv4meu8

idv4meu81#

也许那是可以帮助你解决问题的东西:

import groovy.xml.XmlParser
import groovy.xml.XmlNodePrinter
import groovy.xml.XmlUtil

println "Parse the XML file ....."
def parser = new XmlParser()
def xml = parser.parseText(
    new File('report.xml').getText('UTF-8')
)

println "Remove everything except XML reports ....."
xml.findAll {
    !it.@file.endsWith('.xml')
}.each { xml.remove(it) }

println "Print to the output file ....."
def printer = new XmlNodePrinter(new PrintWriter(new FileWriter("report.xunit")))
printer.setPreserveWhitespace(true)
printer.print(xml)

println "Done."
lp0sw83n

lp0sw83n2#

我的答案也包含了事实测试和时间属性的testsuits节点必须计算。而且XMLNodePrinter是过时的。这里是我建议的代码。

import groovy.util.XmlParser
import groovy.xml.XmlUtil

def inFile = new File('report.xml')
def testsuite = new XmlParser().parseText(inFile.getText('UTF-8'))

testsuite.testcase.each{ if (it.@file.endsWith('.py')) testsuite.remove(it) }

testsuite.@tests = testsuite.testcase.size()
testsuite.@time = testsuite.testcase.@exectime*.toFloat().sum()

def outFile = new File('report.xunit')
outFile.setText(XmlUtil.serialize(testsuite), 'UTF-8')

相关问题