解析XML文件时出现以下问题
这是我的XML文件的一部分
<Staff id="1">
<Measure>
<Rest>
<durationType>quarter</durationType>
</Rest>
<Chord>
<durationType>quarter</durationType>
<Lyrics>
<text>1M1C2</text>
</Lyrics>
</chord>
<Rest>
<durationType>quarter</durationType>
</Rest>
<Chord>
<durationType>quarter</durationType>
<Lyrics>
<text>1M1C4</text>
</Lyrics>
</chord>
</Measure>
<Measure>
<Measure>
<Measure>
</Staff>
行之间有更多标签,但这些是我要使用的标签
我基本上想做的是:
Go through each Measure section
Check if there is a <Rest> or a <Chord>
If <Rest>
output 'REST'
else if <Chord>
output <text>.text
else
do nothing
在此示例中,输出应为
>>> REST
>>> 1M1C2
>>> REST
>>> 1M1C4
我的问题是我可以获取所有REST标签和所有Chord.Lyrics.Text,但顺序不正确。
import xml.etree.ElementTree as msElements
file_Name = '.\\Data\\Demo1.mscx'
msTree = msElements.parse(file_Name)
msRoot = msTree.getroot()
for staff in msRoot.iter('Staff'):
for measure in staff.iter('Measure'):
for voice in measure.iter('voice'):
for chord in (voice.iter('Rest') or voice.iter('Chord')):
for rest in chord.iter('durationType'):
print('REST ')
for text in (chord.iter('text')):
print('TEXT ', text.text)
输出为:
REST
REST
REST
REST
我知道 “用于和弦(voice.iter('Rest')或voice.iter('Chord')):” 是不正确的,但它与我的想法最接近,应该起作用
for chord in (voice.iter('Rest')):
for rest in chord.iter('durationType'):
print('REST ')
for chord in (voice.iter('Chord')):
for text in (chord.iter('text')):
print('TEXT ', text.text)
但是现在我的结果是
REST
REST
1M1C2
1M1C4
我在哪里转错了方向,