3

我在python下使用libxml2。不幸的是,这个库的 python 版本的文档真的很糟糕,我在网上只建立了几个例子,从那里我可以理解一些方法。

我很快管理了添加一个 XML 节点。由于该元素应替换现有元素,因此我想删除之前的元素,但我找不到删除子元素的方法。

有谁知道方法名称是什么?有人有关于这个库的像样的文档吗?

干杯

4

3 回答 3

5

您可以使用该unlinkNode()方法删除给定节点。一般来说,大多数适用于节点的方法都有记录,请尝试:

pydoc libxml2.xmlNode

对于unlinkNode,文档说:

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

例如,给定这个输入:

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

您可以像这样解析文件:

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

像这样定位<div>节点:

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

并像这样删除它:

>>> node.unlinkNode()

现在,如果您打印出文档,您会得到:

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

</body>
</html>
于 2011-10-31T15:07:04.023 回答
1

您的意思是您正在使用lxmllibXML2 的绑定吗?IMO 在http://lxml.de/上对它们进行了很好的记录。

它提到元素是列表。所以你可以使用removelist 函数来删除一个节点。

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>"
于 2011-10-31T13:49:44.090 回答
0

为了完整起见,如果要删除的项目是属性unsetProp是选择的方法:

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

有没有人有关于这个库的像样的文档?

这个 libxml2 文档对我帮助很大。

于 2016-04-04T13:33:45.970 回答