2011-09-14 111 views
0

关于xpath的,蟒一个具体问题,libxml2domxpath - libxml2dom将元素插入到dom中?

假设以下HTML测试

一个如何可以创建蟒/ xpath的逻辑与的xpath相关联的TR之前插入在DOM元素=“// 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> 

我想这个..其中一个 “格” 是围绕TD/TD加..

<html> 
<body> 
<div> 
<tr> 
<td class="foo"> 
</td> 
</tr> 
</div> 
<tr> 
<td> 
</td> 
</tr> 
<div> 
<tr> 
<td class="foo"> 
</td> 
</tr> 
</div> 
</body> 
</html> 

指针/意见..谢谢

回答

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) 

印刷文档然后给你:

<?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根元素坐在那里 - 我敢肯定有人可以想出一种摆脱它的方式!