V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
xchaoinfo
V2EX  ›  Python

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

  •  
  •   xchaoinfo · 2021-01-21 20:45:27 +08:00 · 1200 次点击
    这是一个创建于 1162 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    
    """解析 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
    
    
    2 条回复    2021-01-22 16:27:29 +08:00
    jalena
        1
    jalena  
       2021-01-22 09:14:44 +08:00
    根据我这么些年的开发经验,是否有一个 getElement method ??
    xchaoinfo
        2
    xchaoinfo  
    OP
       2021-01-22 16:27:29 +08:00
    @jalena 并不是单纯的获取所有的 Elements, 还要层级结构,便于格式化的输出
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1035 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 22:37 · PVG 06:37 · LAX 15:37 · JFK 18:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.