2012-10-16 99 views
0

我有一個如下的xml文件,我想從我的設備讀取數據並使用python腳本將數據寫入「value」列。基於屬性在xml中讀取和寫入值

<TopoDefs> 
    <Device Name="SNB" LogicalType="CORE" 
      IdCode="0x03886A21" Mask="0xf0000000"> 
    <Variable name="A0" value="0x52001321" type="GREEN" /> 
    <Variable name="A1" value="0x51001321" type="GREEN" /> 
    <Variable name="A2" value="0x03001321" type="GREEN" /> 
    <Variable name="A3" value="0x14001321" type="GREEN" /> 
    <Variable name="B0" value="0x5A001321" type="BLUE" /> 
    <Variable name="B1" value="0x51001321" type="BLUE" /> 
    <Variable name="B2" value="0x04001321" type="BLUE" /> 
    <Variable name="B3" value="0x05001321" type="BLUE" /> 
    </Device> 
</TopoDefs> 

我完全是一個python腳本的新學習者。如何解析xml文件並指向屬性值以被一個將會一直改變的新值所取代? 如果我使用getElementsByTagName和nodevalue,它會讀取節點的所有字符串,我如何通過只讀取值來限制,而其他變量保持不變?

回答

0

這裏有一個例子是遍歷文件中的所有設備,並在設備的所有變量:

xmlstr = """<TopoDefs> 
    <Device Name="SNB" LogicalType="CORE" 
      IdCode="0x03886A21" Mask="0xf0000000"> 
    <Variable name="A0" value="0x52001321" type="GREEN" /> 
    <Variable name="A1" value="0x51001321" type="GREEN" /> 
    <Variable name="A2" value="0x03001321" type="GREEN" /> 
    <Variable name="A3" value="0x14001321" type="GREEN" /> 
    <Variable name="B0" value="0x5A001321" type="BLUE" /> 
    <Variable name="B1" value="0x51001321" type="BLUE" /> 
    <Variable name="B2" value="0x04001321" type="BLUE" /> 
    <Variable name="B3" value="0x05001321" type="BLUE" /> 
    </Device> 
</TopoDefs>""" 

import xml.etree.ElementTree as ET 
document = ET.fromstring(xmlstr) 

for dev in document.iter('Device'): 
    for var in dev.iter('Variable'): 
     var.set('value', 'new_value') 

print ET.tostring(document)