xpath - libxml2dom 如何向 DOM 插入元素?
这是一个关于xpath、python和libxml2dom的具体问题。
假设我们有以下测试用的html代码。
我们该如何用python和xpath的逻辑,在与xpath="//tr/td[@class='foo']"相关的
我知道libxml2dom有相关的方法可以做到这一点,但我找不到相关的文档或例子来帮助我!
谢谢!
<html>
<body>
<tr>
<td class="foo">
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td class="foo">
</td>
</tr>
</body>
</html>
我想要这样的效果,就是在
<html>
<body>
<div>
<tr>
<td class="foo">
</td>
</tr>
</div>
<tr>
<td>
</td>
</tr>
<div>
<tr>
<td class="foo">
</td>
</tr>
</div>
</body>
</html>
如果有任何建议或评论,请告诉我,谢谢!
1 个回答
0
是的,libxml2的Python绑定文档确实很少。不过,我会这样做...
import libxml2
html = '<html><body><tr><td class="foo"></td></tr><tr><td></td></tr><tr><td class="foo"></td></tr></body></html>'
doc = libxml2.parseDoc(html)
for elem in [xeval.parent for xeval in doc.xpathEval('//tr/td[@class="foo"]')]:
# Create a new div element
newdiv = libxml2.newNode('div')
# Copy current node
node_copy = elem.copyNode(1)
# Append current node copy to new div element
newdiv.addChild(node_copy)
# Replace current node with new div
elem.replaceNode(newdiv)
打印 doc 后,你会看到:
<?xml version="1.0"?>
<html><body><div><tr><td class="foo"/></tr></div><tr><td/></tr><div><tr><td class="foo"/></tr></div></body></html>
我知道,那里有一个XML根元素 - 我相信总有人能想出办法把它去掉!