Python xml pretty print not working

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) # makes pretty print work path3 = 'path_to_xml_file' open(path3) tree = etree.parse(path3, parser) root = tree.getroot() tree.write(xmlFileOut, pretty_print = True, xml_declaration = True, encoding = 'UTF-8') 

This works, but how do I get it to work with the xml string?

+4
source share
2 answers

Taken from http://ruslanspivak.com/2014/05/12/how-to-pretty-print-xml-with-lxml/

 import StringIO import lxml.etree as etree def prettify(xml_text): """Pretty prints xml.""" parser = etree.XMLParser(remove_blank_text=True) file_obj = StringIO.StringIO(xml_text) tree = etree.parse(file_obj, parser) return etree.tostring(tree, pretty_print=True) 
+3
source

A simple solution would be to use StringIO:

 from StringIO import StringIO from lxml import etree parser = etree.XMLParser(remove_blank_text=True) tree = etree.parse(StringIO(templateXml), parser) 
0
source

Source: https://habr.com/ru/post/1496462/


All Articles