写了个把 xml 的 tag 解析目录树的小脚本, 各位大佬提点意见

2021-01-21 20:45:27 +08:00
 xchaoinfo

求问, 各位大佬有没有更好的实现方式


"""解析 xml 的结构为目录树,能够快速的对 xml 的结构有基本的了解。这也是 nonlocal 新关键字的一个 demo
"""
from io import BytesIO

from lxml import etree


def init_xpath(page_source: str):
    """page_source 的 xml 文本转为可以解析的 etree 对象
    """
    xml_root = etree.parse(BytesIO(page_source.encode()))
    return xml_root


def fmt(fg):
    """格式化输出"""
    print("-" * fg, end="")


def tree_xml(root, result, flags=0, step=2):
    result.append((flags, root))

    def tree(root):
        nonlocal flags
        ch_root = root.getchildren()
        if ch_root:
            flags += step
            for ch in ch_root:
                tree_xml(ch, result, flags)
        else:
            pass
    tree(root)
    return result


def main():
    data = """
    <xml>
        <aa>
            <bb></bb>
            <cc>
                <a11></a11>
                <a22>
                    <mue></mue>
                </a22>
            </cc>
            <dd></dd>
        </aa>
        <ee>
            <ff></ff>
        </ee>
    </xml>
    """
    xml_root = init_xpath(data)
    res_xml = tree_xml(xml_root.getroot(), [])
    for fg, _root in res_xml:
        fmt(fg)
        print(_root.tag)


if __name__ == '__main__':
    main()

执行结果是这样的

xml
--aa
----bb
----cc
------a11
------a22
--------mue
----dd
--ee
----ff

1213 次点击
所在节点    Python
2 条回复
jalena
2021-01-22 09:14:44 +08:00
根据我这么些年的开发经验,是否有一个 getElement method ??
xchaoinfo
2021-01-22 16:27:29 +08:00
@jalena 并不是单纯的获取所有的 Elements, 还要层级结构,便于格式化的输出

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/747183

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX