将特定xml标记的值插入到python元组中

时间:2013-04-25 16:15:21

标签: python xml

以下是xml文件:Results.xml

<?xml version="1.0" ?>
<Combinations>
    <Mode>PC</Mode>
    <Category>ADULT</Category>
    <Combination>
        <Parameter>
            <PEEP>1.0</PEEP>
            <Result>true</Result>
        </Parameter>
        <Parameter>
            <CMV_FREQ>4.0</CMV_FREQ>
            <Result>false</Result>
        </Parameter>
    </Combination>
</Combination>

Python代码:

import xml.etree.ElementTree as ET

tree = ET.parse('Results.xml')    
root = tree.getroot()

mode = root.find('Mode').text
category = root.find('Category').text
print mode, category

for combin in root.findall('Combination'):
    peep = rr = []
    for param in combin.getiterator('Parameter'):
    peep.append(((param.get('PEEP'), param.find('PEEP').text), param.find('Result').text))
    rr.append(((param.get('CMV_FREQ'), param.find('CMV_FREQ').text), param.find('Result').text))
    print peep, rr

错误:

Traceback (most recent call last):
  File "/home/AlAhAb65/workspace/python_code/prac1.py", line 59, in <module>
    rr.append(((param.get('CMV_FREQ'), param.find('CMV_FREQ').text), param.find('Result').text))
AttributeError: 'NoneType' object has no attribute 'text'

基本上我想从xml标签获取值到变量内部,如下所示:

peep = ((PEEP, 1.0), true)        # I want to check the tag before enter value and corresponding true will be insert into variable
rr   = ((CMV_FREQ, 4.0), false)

请在这方面帮助我

1 个答案:

答案 0 :(得分:0)

您遇到的问题是,在第一个标签内部没有CMV_FREQ,因此当您尝试使用它时会失败:

>>> for combin in root.findall('Combination'):
...    for param in  combin.getiterator('Parameter'):
...        param.get('CMV_FREQ').text
... 
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
AttributeError: 'NoneType' object has no attribute 'text'

如果你想拥有你上面所需要的东西:

  for combin in root.findall('Combination'):
    peep = []
    rr = []
    print 1
    for param in combin.getiterator('Parameter'):
      if param.find('PEEP') is not None: ##This will check if PEEP tag exists
         peep.append(((param.get('PEEP'), param.find('PEEP').text), param.find('Result').text))
      elif  param.find('CMV_FREQ') is not None:##This will check if CMV_FREQ tag exists
         rr.append(((param.get('CMV_FREQ'), param.find('CMV_FREQ').text), param.find('Result').text))
    print peep, rr

另一个问题 peep = rr = [] 使peep == rr 所以当你改变rr时,窥视也会更新 如果您保留代码,结果应该是

[((None, '1.0'), 'true'), ((None, '4.0'), 'false')] [((None, '1.0'), 'true'), ((None, '4.0'), 'false')]

而不是:

[((None, '1.0'), 'true')] [((None, '4.0'), 'false')]