Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change tab spacing in python lxml prettyprint

I have a small script that creates an xml document and using the prettyprint=true it makes a correctly formatted xml document. However, the tab indents are 2 spaces, and I am wondering if there is a way to change this to 4 spaces (I think it looks better with 4 spaces). Is there a simple way to implement this?

Code snippet:

doc = lxml.etree.SubElement(root, 'dependencies')
for depen in dependency_list:
    dependency = lxml.etree.SubElement(doc, 'dependency')
    lxml.etree.SubElement(dependency, 'groupId').text = depen.group_id
    lxml.etree.SubElement(dependency, 'artifactId').text = depen.artifact_id
    lxml.etree.SubElement(dependency, 'version').text = depen.version
    if depen.scope == 'provided' or depen.scope == 'test':
        lxml.etree.SubElement(dependency, 'scope').text = depen.scope
    exclusions = lxml.etree.SubElement(dependency, 'exclusions')
    exclusion = lxml.etree.SubElement(exclusions, 'exclusion')
    lxml.etree.SubElement(exclusion, 'groupId').text = '*'
    lxml.etree.SubElement(exclusion, 'artifactId').text = '*'
tree.write('explicit-pom.xml' , pretty_print=True)
like image 478
fractalflame Avatar asked Dec 23 '22 17:12

fractalflame


1 Answers

If someone is still trying to achieve this, it can be done using etree.indent() method in lxml 4.5 -

>>> etree.indent(root, space="    ")
>>> print(etree.tostring(root))
<root>
    <a>
        <b/>
    </a>
</root>

https://lxml.de/tutorial.html#serialisation

like image 59
webh Avatar answered Dec 28 '22 08:12

webh