推荐学习书目
› 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 · Jan 21, 2021 · 2050 views
    This topic created in 2079 days ago, the information mentioned may be changed or developed.

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

    
    """解析 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 replies  •  2021-01-22 16:27:29 +08:00
    jalena
        1
    jalena  
       Jan 22, 2021
    根据我这么些年的开发经验,是否有一个 getElement method ??
    xchaoinfo
        2
    xchaoinfo  
    OP
       Jan 22, 2021
    @jalena 并不是单纯的获取所有的 Elements, 还要层级结构,便于格式化的输出
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2207 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 10:28 · PVG 18:28 · LAX 03:28 · JFK 06:28
    ♥ Do have faith in what you're doing.