我是python的新手,想要了解解析xml。关于如何创建一个通用程序来遍历XML节点集,我找不到任何很好的示例或解释。
我希望能够通过名称和值对所有元素和属性进行分类和标识,而不需要任何关于xml模式的信息。我不想依赖于通过标记名或文本来专门调用元素和属性。
有人能给我指个方向吗?
谢谢
更新:
被问到的具体问题是:“如何在不熟悉模式的情况下递归XML文档中从根节点开始的所有节点?”
当时,作为python的新手,并且了解如何在许多其他语言中执行该操作,我对任何不依赖命名节点来遍历DOM的真实示例感到困惑,这根本不是我想要的。
希望这能澄清这个问题,因为这个帖子中的信息确实很有用。
发布于 2012-11-20 11:04:43
请查看ElementTree帮助中的python文档
该页面中的一个基本代码存根是:
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:,直到没有更多的子级。
发布于 2012-11-20 15:14:38
使用cElementTree;它比ElementTree的Python版快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 '$$$$$$$$$$'https://stackoverflow.com/questions/13465807
复制相似问题