2012-05-15 221 views
-1

我有一个xml文件“one”,使用xml.dom解析xml文件

+3

和你尝试过什么? – gefei

+0

什么我尝试是: ' 从进口xml.dom的minidom命名 DOM = minidom.parse中(' sth.xml ') detailList = dom.getElementsByTagName(' 一“)[0] .childNodes 为每个在detailList: print each.tagName ' – ashokadhikari

+0

它不是一个有效的xml文件它应该有一个根 –

回答

0

XML文件应该像格式,如

<?xml version="1.0" ?> 
<ones> 
<one> 
<a>sth</a> 
<b>sth</b> 
<c>sth</c> 
</one> 
<one> 
<a>x</a> 
<b>y</b> 
<c>z</c> 
</one> 
</ones> 

你可以尝试如下代码:

from xml.dom import minidom 

xmldoc = minidom.parse('filePath') 
root = xmldoc.documentElement 

ones = root.getElementsByTagName('one') 

L = [] 
for one in ones: 
    m = {} 
    #print onn.getElementsByTagName('a')[0].childNodes[0].nodeValue 
    #print n.getElementsByTagName('b')[0].childNodes[0].nodeValue 
    #print n.getElementsByTagName('c')[0].childNodes[0].nodeValue 
    for n in one.childNodes: 
     if n.nodeType == n.ELEMENT_NODE: 
       m[n.nodeName] =n.firstChild.nodeValue 
    L.append(m) 
+0

谢谢。现在,如果我想列出一个字典列表 [{'a':sth,'b':sth,'c':sth},{'a':x,'b':y,'c': z}] 这意味着我不提前知道标签名称,并且我想要读取所有存在的数据,tagname:value,我该怎么办? – ashokadhikari

+0

我改变了代码,你可以试试它 –