在xml文件中加载数据

时间:2017-05-26 11:42:29

标签: python

我在名为" sample.xml"

的XML文件中有以下文本
<SpeechSegment spkid="S0">
 <Word dur="0.22" stime="0.44">oh</Word>
 <Word dur="0.27" stime="1.67">bedankt</Word>
 <Word dur="0.3" stime="2.03">voor</Word>
 <Word dur="0.53" stime="2.61">deelname</Word>
</SpeechSegment>

我想加载xml数据,所以我可以像这样:

raw = '''<SpeechSegment spkid="S0">
 <Word dur="0.22" stime="0.44">oh</Word>
 <Word dur="0.27" stime="1.67">bedankt</Word>
 <Word dur="0.3" stime="2.03">voor</Word>
 <Word dur="0.53" stime="2.61">deelname</Word>
</SpeechSegment>'''

from xml.etree import ElementTree as ET
root = ET.fromstring(raw)
result = [word.text for word in root.findall('Word')]
print result

但问题是我似乎无法从xml文件加载数据。我试着这样做:

import xml.etree.ElementTree as ET
raw2 = ET.parse('Interview_short.xml')

但是这不起作用:

from xml.etree import ElementTree as ET
root = ET.fromstring(raw2)
result = [word.text for word in root.findall('Word')]
print result

2 个答案:

答案 0 :(得分:0)

您在parse(**Interview_short.xml**)中使用了不同的文件。您说您的数据位于文件**sample.xml**中 以下工作正常:

import xml.etree.ElementTree as ET
raw2 = ET.parse('sample.xml')
print([word.text for word in raw2.findall('Word')])

答案 1 :(得分:0)

以下xml.etree.elementTree soup = BeautifulSoup(...) items = soup.find_all('a') for item in items: if item.parent.name != u'p': item.wrap(soup.new_tag('p')) ET.parse的文档不能一起用于获取xml的根元素。 要么在ET.fromstring返回的树上调用raw2.getroot(),要么将整个xml-string提供给ET.parse方法,例如使用open。

小例子:

ET.fromstring