用minidom解析python xml

时间:2014-01-27 13:22:49

标签: python xml parsing minidom

我有这个XML文件 我需要以与XML文件中相同的顺序读取Sync和Event中的值。

<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

有什么解决方案吗?谢谢。

3 个答案:

答案 0 :(得分:0)

使用builtin 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())

答案 1 :(得分:0)

除非你以某种方式限制使用Minidom,否则请尝试使用Martijn建议的'ElementTree'。根据我的个人经验,它更容易使用。你可以找到它的文档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是所有标签属性的映射。

答案 2 :(得分: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
相关问题