我需要从这个XML文件中读取数据。我不知道,我如何从这个XML文件中读取数据aaaaa,bbbbb,ccccc,ddddd,eeeee,fffff和ggggg。
<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>
我写这段代码:
# -*- 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
输出是:
sp1
sp2
sp3
但输出应该是:
sp1
aaaaa
bbbbb
sp2
ccccc
ddddd
eeeee
sp3
fffff
ggggg
有什么建议吗?谢谢。
答案 0 :(得分:2)
一种方法是获取每个nextSibling
节点的Sync
:
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()
打印:
spk1
aaaaa
bbbbb
spk2
ccccc
ddddd
eeeee
spk3
fffff
ggggg
此外,通过获取每个ElementTree
节点的tail
,您可以使用Sync
获得相同的结果:
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()
希望有所帮助。