I am changing some xml by adding some nodes and values ββfrom the list. I can successfully create all new tags and values, I create them between the participant tags, but when I save the xml to a new file, the tags that I create are on the same line. Here is an example of my code:
templateXml = """<?xml version="1.0" encoding="utf-8" standalone="yes"?> <package> <delivery_type>new</delivery_type> <feature> <feature_type>Movie</feature_type> <contributors> </contributors> </package>""" from lxml import etree tree = etree.fromstring(templateXml) node_video = tree.xpath('//feature/contributors')[0] for cast in castList: pageElement = etree.SubElement(node_video, 'contributor') node_video1 = tree.xpath('//feature/contributors/contributor')[0] pageElement.attrib['type'] = 'cast' pageElement1 = etree.SubElement(pageElement, 'name') pageElement1.text = cast.text pageElement2 = etree.SubElement(pageElement, 'role') pageElement2.text = "actor" xmlFileOut = '/Users/User1/Desktop/Python/Done.xml' with open(xmlFileOut, "w") as f: f.write(etree.tostring(tree, pretty_print = True, xml_declaration = True, encoding='UTF-8', standalone="yes"))
The xml file is saved here:
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <package> <delivery_type>new</delivery_type> <feature> <feature_type>Movie</feature_type> <contributors> <contributor type="cast"><name>John Doe</name><role>actor</role></contributor><contributor type="cast"><name>Another Actors name</name><role>actor</role></contributor><contributor type="cast"><name>Jane Doe</name><role>actor</role></contributor><contributor type="cast"><name>John Smith</name><role>actor</role></contributor></contributors> </package>
I solved this problem when opening an xml file to work with the code below:
from lxml import etree parser = etree.XMLParser(remove_blank_text=True)
This works, but how do I get it to work with the xml string?
source share