【发布时间】: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