Skip to content Skip to sidebar Skip to footer

How To Use Lxml And Python To Pretty Print A Subtree Of An Xml File?

I have the following code using python with lxml to pretty print the file example.xml: python -c ' from lxml import etree; from sys import stdout, stdin; parser=etree.XMLParser(re

Solution 1:

We can capture a nested Element using xpath. Element objects do not provide the same .write() capability so we'll need to a different output mechanism.

How about...

python -c 'from lxml import etree;
from sys import stdout, stdin;

parser=etree.XMLParser(remove_blank_text=True, strip_cdata=False);
tree=etree.parse(stdin, parser)
# assuming there will be exactly 1 project
project=tree.xpath("project")[0]
print etree.tostring(project, pretty_print = True)' < example.xml

Solution 2:

You can use tree.find to get the xml element you need extracted. Them convert it to element tree. Then you can issue a write statement on the resulting elementtree (et) in this case.

python -c 'from lxml import etree;
           from sys import stdout, stdin;
           parser=etree.XMLParser(remove_blank_text=True,strip_cdata=False);
           tree=etree.parse(stdin, parser)
           e = tree.find("project")
           et = etree.ElementTree(e)                                                                                                                                                                             
           et.write(stdout, pretty_print = True)'

Post a Comment for "How To Use Lxml And Python To Pretty Print A Subtree Of An Xml File?"