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

2024-09-27 23:24:09 发布

您现在位置:Python中文网/ 问答频道 /正文

从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个深度和打印的遍历路径数。你知道吗


Tags: childforlentagrootxpathetreeprint
1条回答
网友
1楼 · 发布于 2024-09-27 23:24:09

通过使用lxml的^{}方法,可以大大简化这个过程。你知道吗

这是输入.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

相关问题 更多 >

    热门问题