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.
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.
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().
Looks like it is no another way. Even lxml maintainer Stefan Behnel has proposed addprevious method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With