我的任务就是做XML树的一些元素的微小的重构在Python 3,即替换以下结构:条件移除元素的
<span class="nobr">
<a href="http://www.google.com/">
http://www.google.com/
<sup>
<img align="absmiddle" alt="" border="0" class="rendericon" height="7" src="http://jira.atlassian.com/icon.gif" width="7"/>
</sup>
</a>
</span>
有了:
<span class="nobr">
<a href="http://www.google.com/">
http://www.google.com/
</a>
</span>
即 - 如果整个结构与第一个例子中给出的结构完全一致,请移除sup元素。我需要在处理过程中保留XML文档,所以正则表达式匹配不是可能的。
我已经有代码的工作,我的目的:
doc = self.__refactor_links(doc)
...
def __refactor_links(self, node):
"""Recursively seeks for links to refactor them"""
for span in node.childNodes:
replace = False
if isinstance(span, xml.dom.minidom.Element):
if span.tagName == "span" and span.getAttribute("class") == "nobr":
if span.childNodes.length == 1:
a = span.childNodes.item(0)
if isinstance(a, xml.dom.minidom.Element):
if a.tagName == "a" and a.getAttribute("href"):
if a.childNodes.length == 2:
aurl = a.childNodes.item(0)
if isinstance(aurl, xml.dom.minidom.Text):
sup = a.childNodes.item(1)
if isinstance(sup, xml.dom.minidom.Element):
if sup.tagName == "sup":
if sup.childNodes.length == 1:
img = sup.childNodes.item(0)
if isinstance(img, xml.dom.minidom.Element):
if img.tagName == "img" and img.getAttribute("class") == "rendericon":
replace = True
else:
self.__refactor_links(span)
if replace:
a.removeChild(sup)
return node
这一次不会通过所有的标签递归地运行 - 如果它匹配相似,它寻求结构的东西 - 即使它失败,它不会继续寻找这些元素内部的结构,但在我的情况下,我不应该这样做(虽然这也会很好,但是增加一堆其他成本:self .__ refactor_links(tag)kill它在我眼中)。
如果任何条件失败,则不应该发生移除。有没有更清晰的方式来定义一组条件,避免大量'ifs'?一些自定义数据结构可以用于存储条件,例如, ('sup',('img',(...))),但我不知道应该如何处理它。如果你在Python中有任何建议或例子 - 请帮忙。
谢谢。
Ouch。 'import this'':'... Flat比嵌套更好。 ...' – 2010-11-12 00:38:23