Question

I am using libxml2 under python. Unfortunatly the python version of this library is really badly documented and i founded just few example on the web from there i could understand some of the method.

I managed the add a soon te a XML Node. Since this element should replace an existing one I would like to remove the previos one before but i could not find which is the method to remove a child.

Does anyone know what is the method name? does anyone have a decent documentation about this library?

Cheers

Was it helpful?

Solution

You can use the unlinkNode() method to remove a given node. In general, most of the methods that apply to nodes are documented, try:

pydoc libxml2.xmlNode

For unlinkNode, the documentation says:

unlinkNode(self)
    Unlink a node from it's current context, the node is not
    freed

For example, given this input:

<html>
  <head>
    <title>Document Title</title>
  </head>
  <body>
    <div id="content">This is a test.</div>
  </body>
</html>

You can parse the file like this:

>>> import libxml2
>>> doc = libxml2.parseFile('input.html')

Locate the <div> node like this:

>>> node = doc.xpathEval('//*[@id="content"])[0]

And remove it like this:

>>> node.unlinkNode()

And now if you print out the document, you get this:

>>> print doc
<head>            
    <title>Document Title</title>
</head>
<body>

</body>
</html>

OTHER TIPS

Do you mean that you are using the lxml bindings for libXML2? They're documented reasonably well IMO at http://lxml.de/.

It mentions that elements are lists. So you can use the remove list function to remove a node.

import lxml
root = lxml.etree.Element("root")
child2 = lxml.etree.SubElement(root, "child2")
child3 = lxml.etree.SubElement(root, "child3")
print lxml.etree.tostring(root)
#    "<root><child2/><child3/></root>"
root.remove( child2 )
print lxml.etree.tostring(root)
#    "<root><child3/></root>"

For the sake of completeness, if the item you want to remove is an attribute unsetProp is the method of choice:

...
if node.hasProp('myAttributeName'):
   node.usetProp('myAttributeName')

Does anyone have a decent documentation about this library?

This libxml2 documentation helped me alot.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top