如何使用Python在lxml树上进行最佳迭代(宽度优先)



我试着把我的头围绕lxml(这是新的),以及如何使用它来做我想做的事情。我得到了一个格式良好的有效XML文件

<root>
  <a>
    <b>Text</b>
    <c>More text</c>
  </a>
  <!-- some comment -->
  <a>
    <d id="10" />
  </a>
</root>

像这样。现在我想以广度优先访问这些孩子,我能想到的最好的方法是这样:

for e in xml.getroot()[0].itersiblings() :
    print(e.tag, e.attrib)

,然后从那里开始。然而,这给了我所有元素,包括注释

a {}
<built-in function Comment> {}
a {}

如何跳过注释?有没有更好的方法来遍历节点的直接子节点?

一般来说,解析XML树和使用事件驱动的拉解析(例如使用iterparse())的建议是什么?

适合你的情况

for child in doc.getroot().iterchildren("*"):
    print(child.tag, child.attrib)

这个问题在9年前就有人问过了,但我自己刚刚遇到这个问题,我用以下方法解决了它

import xml.etree.ElementTree as ET
xmlfile = ET.parse("file.xml")
root = xmlfile.getroot()
visit = [root]
while len(visit):
  curr = visit.pop(0)
  print(curr.tag, curr.attrib, curr.text)
  visit += list(curr)

list(node)将给出该节点的所有直接子节点的列表。因此,通过将这些子元素添加到堆栈中,并对堆栈顶部的元素重复此过程(同时将其弹出),我们应该最终得到标准的宽度优先搜索。

最新更新