Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Adding top level comments by lxml

Tags:

python

xml

lxml

I am using the python2.6 and lxml, I want to add the top level comments into the xml like this

<?xml version='1.0' encoding='UTF-8'?>
<!--top level comment-->
<DCSubtitle/>

I google this addprevious() method to do that, Here is my code:

root = ET.Element("DCSubtitle")
root.addprevious(ET.Comment('top level comment'))
tree = ET.ElementTree(root)
tree.write(sys.stdout, pretty_print=True, xml_declaration=True, encoding='UTF-8')

But, the addprevious() seems to be not very logical, you have to add the second line and then you add the first line, is there any better logical way to do that? Thanks.

like image 686
Liao Zhuodi Avatar asked Apr 12 '14 02:04

Liao Zhuodi


People also ask

What does HTML Fromstring do?

fromstring . This provides us with an object of HtmlElement type. This object has the xpath method which we can use to query the HTML document. This provides us with a structured way to extract information from an HTML document.

How do you process XML in Python?

To read an XML file using ElementTree, firstly, we import the ElementTree class found inside xml library, under the name ET (common convension). Then passed the filename of the xml file to the ElementTree. parse() method, to enable parsing of our xml file. Then got the root (parent tag) of our xml file using getroot().


1 Answers

Looks like it is no another way. Even lxml maintainer Stefan Behnel has proposed addprevious method.

like image 177
Alex Pertsev Avatar answered Sep 21 '22 10:09

Alex Pertsev