1

I'm using xml.etree.ElementTree to parse an xml file in the form-

<element> 
   <status>OK</status> 
   <duration> 
    <value>340110</value> 
    <text>3 jours 22 heures</text> 
   </duration> 
   <distance> 
    <value>1734542</value> 
    <text>1 735 km</text> 
   </distance> 
  </element> 

I am then separating out the time values and comparing them to get the smallest possible value. However, I'm not sure how to do this without also ending up getting the distance value, which messes up my dataset. This is the code I have so far for fetching anything under the values root-

import xml.etree.ElementTree as ET
times=[]
for i in htmlSource:
    root=ET.fromstring(i)
    for value in root.iter('value'):
        times.append(value.text)

Is there a way I can modify this to only get the values under duration and not distance? Thank you in advance.

4

1 回答 1

0

我实际上设法弄清楚了这一点。我还需要使值的索引与原始数据保持一致,这很困难,因为任何时候元素的状态发生变化时都不会出现“值”部分,并且所有后续值的索引都会因缺少而增加. 这是我对那个问题和我原来的问题的解决方案。

for i in htmlSource: 
    root=ET.fromstring(i) #parses the data
    for element in root.iter('element'):
        if element[0].text == 'OK'
            Temp=element[1][0].text #finds the time value
            times.append(Temp) #adds the time value to a list
        else:
            times.append(0)

element[1][0] 表示指定元素的第二个根的第一个“孩子”,这是所需的值根,而 .text 为我提供了该根的文本内容。element[0] 是状态,元素下的第一个根。

于 2014-06-23T15:31:18.390 回答