如何在元素树中迭代期间替换元素? 我正在为markdown编写一个树处理器,并希望包装一个元素。
<pre class='inner'>...</pre>应该成为
<div class='wrapper'><pre class='inner'>...</pre></div>我使用getiterator('pre')来查找元素,但我不知道如何包装它。 问题点是用新的包装器替换找到的元素,但保留现有元素作为子包装。
How can I replace an element during iteration in an elementtree? I'm writing a treeprocessor for markdown and would like to wrap an element.
<pre class='inner'>...</pre>Should become
<div class='wrapper'><pre class='inner'>...</pre></div>I use getiterator('pre') to find the elements, but I don't know how to wrap it. The trouble point is replacing the found element with the new wrapper, but preserving the existing one as the child.
最满意答案
这有点棘手。 首先,您需要获取上一个问题中描述的父元素。
parent_map = dict((c, p) for p in tree.getiterator() for c in p)如果你可以降价使用lxml ,这会更容易一点 - 我相信lxml元素已经知道了他们的父母。
现在,当您从迭代中获取元素时,您还可以获取父元素:
for elem in list(tree.getiterator('pre')): parent = parent_map[elem] wrap_elem(parent, elem)请注意,我已经将树中的迭代器转换为列表 - 我们不希望在迭代它时修改树。 那可能是个麻烦。
最后,您可以移动元素:
def wrap_elem(parent, elem) parent_index = list(parent).index(elem) parent.remove(elem) new_elem = ET.Element('div', attrib={'class': 'wrapper'}) parent.insert(parent_index, new_elem) new_elem.append(elem)*请注意,我没有完全测试此代码...如果您发现任何错误,请告诉我。
This is a bit of a tricky one. First, you'll need to get the parent element as described in this previous question.
parent_map = dict((c, p) for p in tree.getiterator() for c in p)If you can get markdown to use lxml, this is a little easier -- I believe that lxml elements know their parents already.
Now, when you get your element from iterating, you can also get the parent:
for elem in list(tree.getiterator('pre')): parent = parent_map[elem] wrap_elem(parent, elem)Note that I've turned the iterator from the tree into a list -- We don't want to modify the tree while iterating over it. That could be trouble.
Finally, you're in position to move the element around:
def wrap_elem(parent, elem) parent_index = list(parent).index(elem) parent.remove(elem) new_elem = ET.Element('div', attrib={'class': 'wrapper'}) parent.insert(parent_index, new_elem) new_elem.append(elem)*Note that I haven't tested this code exactly... let me know if you find any bugs.
更多推荐
发布评论