2014-01-27 101 views
1

我有这个XML文件 ,我需要按照与XML文件中相同的顺序读取Sync和Event中的值。python xml用minidom解析

<Episode> 
<Section type="report" startTime="0" endTime="263.035"> 
    <Turn startTime="0" endTime="4.844" speaker="spk1"> 
     <Sync time="0"/> 
     aaaaa 
    </Turn> 
    <Turn speaker="spk2" startTime="4.844" endTime="15.531"> 
     <Sync time="4.844"/> 
     bbbbb 
     <Event desc="poz" type="noise" extent="begin"/> 
     ccccc 
     <Event desc="poz" type="noise" extent="end"/> 
     ddddd 

    <Sync time="12.210"/> 
     eeeee 
    </Turn> 
    <Turn speaker="spk1" startTime="15.531" endTime="17.549"> 
     <Event desc="poz" type="noise" extent="begin"/> 
     fffff 
    </Turn> 
</Section> 
</Episode> 

我需要这样的输出:

aaaaa 
bbbbb 
ccccc 
ddddd 
eeeee 
fffff 

有没有什么解决办法吗?谢谢。

+0

你为什么要使用minidom命名? [documentation](http://docs.python.org/2/library/xml.dom.minidom.html#module-xml.dom.minidom)警告不要使用它(DOM是冗长和古老的方式),建议您改用[ElementTree API](http://docs.python.org/2/library/xml.etree.elementtree.html#module-xml.etree.ElementTree)。 –

回答

0

使用内置SAX解析器:

from xml import sax 

class EpisodeContentHandler(sax.ContentHandler): 
    def characters(self, content): 
     content = content.strip() 
     if content: 
      print content 

with open("Episode.xml") as f: 
    sax.parse(f, EpisodeContentHandler()) 
0

除非你以某种方式限于使用minidom命名,请尝试使用 'ElementTree的' 作为建议的Martijn。从我个人的经验来看,使用起来要容易得多。你可以找到它的文档here

对于你的问题,你可以尝试这样的事:

import xml.etree.ElementTree as ET 

# Get the tree structure of the XML 
tree = ET.parse("data.xml") 
# Get the root/first tag in the tree 
root = tree.getroot() 
# Ge all elements with interesting tags 
for child in root.findall("Sync"): 
    print child.text 

旁注:child.attrib是一个映射到所有标签的属性。

+0

谢谢,但是这段代码不起作用。有没有办法用minidom来做到这一点?或者我必须使用ElementTree ... – user3240368

0

如果你坚持使用minidom命名上:

elements = minidom.parseString(xml).getElementsByTagName('*') # where xml is your input xml 
for el in elements: 
    if el.localName == 'Sync' or el.localName == 'Event': 
     print el.nextSibling.nodeValue.strip() 

这将打印:

aaaaa 
bbbbb 
ccccc 
ddddd 
eeeee 
fffff