0

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&#xD;&#xA;" /> 

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?

1
  • 1
    If you don't want sub-elements, don't use SubElement... Commented Aug 25, 2021 at 6:00

1 Answer 1

1

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> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.