【问题标题】:implementing DFS or recursion and printing the traversed path in python在python中实现DFS或递归并打印遍历的路径
【发布时间】:2018-02-24 05:35:24
【问题描述】:

从 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 个深度并打印遍历路径的解决方案。

【问题讨论】:

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


    【解决方案1】:

    你可以通过使用 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
    

    【讨论】:

    • 感谢您的解决方案,但您能否也对我的代码进行必要的更改,这将有助于我构建我的概念。谢谢
    猜你喜欢
    • 2011-11-27
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 2020-04-01
    • 2015-03-02
    • 2021-06-11
    • 2023-03-29
    相关资源
    最近更新 更多