实现DFS或递归并在python中打印遍历的路径

时间:2018-02-24 05:35:24

标签: python python-3.x beautifulsoup lxml depth-first-search

从XML创建绝对路径。

我创建了一个xml

from lxml import etree

root = etree.Element("root1")
child1 = etree.SubElement(root, "child1")
child2 = etree.SubElement(root, "child2")
child21 = etree.SubElement(child2, "child21")
child201 = etree.SubElement(child21, "child221")
child3 = etree.SubElement(root, "child3")
print(etree.tostring(root, pretty_print=True))

现在我必须打印遍历的路径,如

/root1/child1
/root1/child2

util child没有更多的孩子

到目前为止,我已经找到了解决方案

xpathlist = []

if len(root):
    print(len(root))
    for child in root:
        print(child)
        xpath_1 = "/" + root.tag + "/" + child.tag
        xpathlist.append("".join(xpath_1.split()))
        if len(child):
            for minichild in child:
                print(minichild)
                xpath_1 = "/" + root.tag + "/" + child.tag + "/" + minichild.tag
                xpathlist.append("".join(xpath_1.split()))

for xx in xpathlist:
    print(xx)

给出了以下输出

/root1/child1
/root1/child2
/root1/child2/child21
/root1/child3

但正如您所见,缺少一条路径

/root1/child2/child21/child221

因为它的深度更深,我的代码无法处理,并且可以创建更多的深度。

需要一种能够处理N个深度并打印遍历路径的解决方案。

1 个答案:

答案 0 :(得分:2)

您可以使用lxml' getpath()方法对此进行简化。

这是input.xml:

<root1>
  <child1/>
  <child2>
    <child21>
      <child221/>
    </child21>
  </child2>
  <child3/>
</root1>

以下是如何为XML文档中的每个元素生成绝对XPath表达式:

from lxml import etree

tree = etree.parse("input.xml")

for elem in tree.iter():
    print(tree.getpath(elem))

输出:

/root1
/root1/child1
/root1/child2
/root1/child2/child21
/root1/child2/child21/child221
/root1/child3