Marc,
I understand how the append(fragment) approach shown in your example can be
used to successfully add an XML Comment that is a child of the root element
(see example code below), but I don't see how that approach can be used to
add a top-level comment.
(Also, I neglected to include the result of the print statement that shows
the top-level comment in my original post. This time the result of the
print statement, which shows an example of a top-level comment, is included
below.)
- Tyler
##########################################################
# Example of using the append(fragment) approach to add a (not top level)
comment
##########################################################
$ python
Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
from lxml import etree
from lxml.builder import E
# construct an Element class using the E-factory
... element = (
... E.root(
... E.a('eggs'),
... )
... )
# wrap with an ElementTree
... element_tree = etree.ElementTree(element)
# append a comment to the root
... element_tree.getroot().append(etree.Comment('test comment'))
print etree.tostring(element_tree,pretty_print=True)
<root>
<a>eggs</a>
<!--test comment-->
</root>
##########################################################
# Example of a top-level comment
##########################################################
from StringIO import StringIO
tree = etree.parse(StringIO('''\
... <?xml version="1.0"?>
... <!-- sample top level comment -->
... <root>
... <a>eggs</a>
... </root>
... '''))
print etree.tostring(tree)
<!-- sample top level comment --><root>
<a>eggs</a>
</root>
On Mon, Feb 28, 2011 at 2:37 PM, Graff, Marc <Marc.Graff@verizonwireless.com
wrote:
Attached is a method I use to insert external xml into an existing tree
Then I print out the modified tree after all mods are complete.
*From:* lxml-bounces@lxml.de [mailto:lxml-bounces@lxml.de] *On Behalf Of *Tyler
Erickson
*Sent:* Monday, February 28, 2011 3:14 PM
*To:* lxml@lxml.de
*Subject:* [lxml] Adding top-level comments to an ElementTree object
How do you add top-level comments to an ElementTree object [1]?
from lxml import etree
from lxml.builder import E
# construct an Element class using the E-factory
element = (
E.root(
E.a('eggs'),
)
)
# wrap with an ElementTree
element_tree = etree.ElementTree(element)
It appears that you can do this by parsing an XML document that contains a
top-level comment (shown below), but I am unsure of how to add a top-level
comment to an existing ElementTree object.
from StringIO import StringIO
tree = etree.parse(StringIO('''\
<?xml version="1.0"?>
<!-- sample top level comment -->
<root>
<a>eggs</a>
</root>
'''))
print etree.tostring(tree)
- Tyler
[1] http://lxml.de/tutorial.html#the-elementtree-class