【问题标题】:XML walking in python [closed]XML在python中行走[关闭]
【发布时间】:2012-11-08 02:00:24
【问题描述】:

我是 python 新手,想了解解析 xml。我还没有找到任何很好的例子或解释如何创建一个通用程序来遍历 XML 节点集。

我希望能够按名称和值对所有元素和属性进行分类和识别,而无需任何有关 xml 架构的信息。我不想依赖专门通过标签名称或文本调用元素和属性。

有人可以指点我正确的方向吗?

谢谢

更新:

被问到的具体问题是,“我一般如何在不了解架构的情况下从 XML 文档中的根节点递归所有节点。”

当时,刚接触 python 并了解如何在许多其他语言中执行该操作,我对任何不依赖命名节点遍历 DOM 的真实示例感到困惑,这不是我完全想要。

希望这可以澄清问题,因为该线程中的信息确实有用。

【问题讨论】:

  • 你尝试过什么吗?看看lxml。
  • 嗨,我不知道为什么这被关闭为“不是一个真正的问题”?我问了一个非常具体的问题,并且对试图理解的概念相当准确。我的问题有什么问题,这样我就不会再犯同样的错误了?

标签: python xml lxml elementtree


【解决方案1】:

使用 cElementTree; 它比 Python 版本的 ElementTree 快 15-20 倍,并且使用的内存减少了 2-5 倍。 http://effbot.org/zone/celementtree.htm

import xml.etree.cElementTree as ET
tree = ET.parse('test.xml')
for elem in tree.getiterator():
    if elem.tag:
        print 'my name:'
        print '\t'+elem.tag
    if elem.text:
        print 'my text:'
        print '\t'+(elem.text).strip()
    if elem.attrib.items():
        print 'my attributes:'
        for key, value in elem.attrib.items():
            print '\t'+'\t'+key +' : '+value
    if list(elem): # use elem.getchildren() for python2.6 or before
        print 'my no of child: %d'%len(list(elem))
    else:
        print 'No child'
    if elem.tail:
        print 'my tail:'
        print '\t'+'%s'%elem.tail.strip()
    print '$$$$$$$$$$'

【讨论】:

    【解决方案2】:

    查看python帮助中ElementTree的文档

    该页面的基本代码存根是:

        import xml.etree.ElementTree as ET
        tree = ET.parse(filename)
        root = tree.getroot()
        for child in root:  
          child.tag, child.attrib
    

    你可以继续向下递归运行for child in root:,直到没有更多的孩子。

    【讨论】:

    • 谢谢!正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 2010-09-05
    • 2010-10-04
    相关资源
    最近更新 更多