Bay*_*tch 4 python xml lxml elementtree
我是python新手,想了解解析xml。我还没有找到关于如何创建通用程序以遍历XML节点集的出色示例或说明。
我希望能够通过名称和值来分类和标识所有元素和属性,而无需任何有关xml模式的信息。我不想依靠标记名称或文本来专门调用元素和属性。
有人能指出我正确的方向吗?
谢谢
更新:
提出的具体问题是:“我通常如何在不了解任何架构的情况下从XML文档中的根节点中递归所有节点”。
那时,由于是python的新手,并且了解如何以许多其他语言执行该操作,因此,我对不依赖命名节点遍历DOM的任何现实示例感到困惑,这根本不是我想要的。
希望这可以澄清问题,因为该线程中的信息确实有用。
在python帮助中查看ElementTree的文档
该页面的基本代码存根是:
import xml.etree.ElementTree as ET
tree = ET.parse(filename)
root = tree.getroot()
for child in root:
child.tag, child.attrib
Run Code Online (Sandbox Code Playgroud)
您可以继续for child in root:递归向下运行,直到没有更多孩子为止。
使用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 '$$$$$$$$$$'
Run Code Online (Sandbox Code Playgroud)