擅长:python、mysql、java
<p>我有一个类似的问题,我有点创造性。结果没有什么能阻止我们自己添加亲子信息。一旦我们不再需要它,我们可以把它脱掉。</p>
<pre><code>def addParentInfo(et):
for child in et:
child.attrib['__my_parent__'] = et
addParentInfo(child)
def stripParentInfo(et):
for child in et:
child.attrib.pop('__my_parent__', 'None')
stripParentInfo(child)
def getParent(et):
if '__my_parent__' in et.attrib:
return et.attrib['__my_parent__']
else:
return None
tree = ...
addParentInfo(tree.getroot())
el = tree.findall(...)[0]
parent = getParent(el)
while parent:
...
parent = getParent(parent)
...
stripParentInfo(tree.getroot())
</code></pre>