简体   繁体   中英

python xml parse (minidom)

I need to read data from this XML file. I don´t know, how I have to read data aaaaa, bbbbb, ccccc, ddddd, eeeee, fffff and ggggg from this XML file.

<Episode>
<Section type="report" startTime="0" endTime="10">
    <Turn startTime="0" endTime="2.284" speaker="spk1">
        <Sync time="0"/>
        aaaaa
        <Sync time="0.93"/>
        bbbbb
    </Turn>
    <Turn speaker="spk2" startTime="2.284" endTime="6.458">
        <Sync time="2.284"/>
        ccccc
        <Sync time="3.75"/>
        ddddd
        <Sync time="4.911"/>
        eeeee
    </Turn>
    <Turn speaker="spk3" startTime="6.458" endTime="10">
        <Sync time="6.458"/>
        fffff
        <Sync time="8.467"/>
        ggggg
    <Sync time="9.754"/>

    </Turn>
</Section>
</Episode>

I write this code:

# -*- coding: UTF-8-*-

from xml.etree import ElementTree as ET
import os
from xml.dom import minidom

dom = minidom.parse("aaa.trs")

conference=dom.getElementsByTagName('Turn')
for node in conference:
    conf_name=node.getAttribute('speaker')
    print conf_name
    sync=node.getElementsByTagName('Sync')
    for s in sync:
        s_name=s.getAttribute('time')
        print s_name

Output is:

sp1
sp2
sp3

But the output should be:

sp1
aaaaa
bbbbb
sp2
ccccc
ddddd
eeeee
sp3
fffff
ggggg

Any suggestions? Thank you.

One way is to get the nextSibling of every Sync node:

conference = dom.getElementsByTagName('Turn')
for node in conference:
    conf_name = node.getAttribute('speaker')
    print conf_name
    sync = node.getElementsByTagName('Sync')
    for s in sync:
        print s.nextSibling.nodeValue.strip()

prints:

spk1
aaaaa
bbbbb
spk2
ccccc
ddddd
eeeee
spk3
fffff
ggggg

Also, you can achieve the same result with ElementTree by getting the tail of each Sync node:

tree = ET.parse("aaa.trs")
for turn in tree.findall('.//Turn'):
    print turn.attrib.get('speaker')
    for sync in turn.findall('.//Sync'):
        print sync.tail.strip()

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM