如何替换树中的元素?(How to replace an element in a tree? (elementtree/markdown))

编程入门 行业动态 更新时间:2024-10-24 08:26:11
如何替换树中的元素?(How to replace an element in a tree? (elementtree/markdown))

如何在元素树中迭代期间替换元素? 我正在为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.

更多推荐

本文发布于:2023-07-28 18:58:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1308130.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   replace   element   markdown   elementtree

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!