Reputation: 2227
I am creating an xml
file using python which is giving out the following output.
<?xml version="1.0" ?>
<testsuites>
<testsuite>
<name>ABC</name>
<id>9022e01f-8b0c-4a47-86de-b41192116149</id>
<tests>2048</tests>
<failures>0</failures>
<log> </log>
<testcase>
<Name>HomePage</Name>
<Pass>420</Pass>
<Fail>0</Fail>
<Log> </Log>
Desired output is this
<?xml version="1.0" encoding="utf-8"?>
<testsuites>
<testsuite name="ABC" tests="%%%%%%%" failures="%%%%%%%%" failed="%%%%%%%" id="39fd646d-526a-c4f4-10bb-05366a09b2ea" log="">
<testcase name="TTTTTTTTTTTT" log="+ SSSSSSSS TTTTTTTTTTTT
" />
This is the code I am using
root = ET.Element("testsuites")
doc = ET.SubElement(root, "testsuite")
ET.SubElement(doc, "name").text = "ABC"
ET.SubElement(doc, "id").text = str(uuid.uuid4())
ET.SubElement(doc, "tests").text = f"{total_tests}"
ET.SubElement(doc, "failures").text = f"{failed}"
ET.SubElement(doc, "log").text = " "
tree = ET.ElementTree(root)
doc2 = ET.SubElement(doc, "testcase")
for na, tot, pa, fa in zip(tcname, tctotal, tcpasses, tcfails):
ET.SubElement(doc2, "Name").text = f"{na}"
#ET.SubElement(doc2, "Total Tests").text = f"{tot}"
ET.SubElement(doc2, "Pass").text = f"{pa}"
ET.SubElement(doc2, "Fail").text = f"{fa}"
ET.SubElement(doc2, "Log").text = " "
xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent=" ")
with open("Test.xml", "w", encoding='utf-8') as f:
f.write(xmlstr)
How can I get the desired format?
Upvotes: 0
Views: 27
Reputation: 168913
The SubElement
convenience function accepts a dict of attributes.
import uuid
from xml.etree import ElementTree as ET
root = ET.Element("testsuites")
suite = ET.SubElement(
root,
"testsuite",
{
"name": "ABC",
"id": str(uuid.uuid4()),
"tests": "123",
"failures": "456",
"log": "",
},
)
case = ET.SubElement(
suite,
"testcase",
{
"name": "ttt",
"log": "lll",
},
)
print(ET.tostring(root, "unicode"))
outputs (prettified here)
<testsuites>
<testsuite name="ABC" id="6eaa04eb-b915-43ba-b949-7be1f0af9d4a" tests="123" failures="456" log="">
<testcase name="ttt" log="lll"/>
</testsuite>
</testsuites>
Upvotes: 1