基于属性键以xml写入数据

时间:2012-10-17 16:48:56

标签: python xml

我有一个xml文件,如下所示,我想从我的设备读取数据,并使用python脚本将数据写入某个名称的“value”列。

<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>

我可以问一下如何指向变量A0来写一个关于“value”属性的新数据吗? find,findall,iterfind,itertext之间有什么区别?

1 个答案:

答案 0 :(得分:1)

使用lxml,我认为这是该任务可用的最佳工具:

from lxml import etree as ET


>>> root = ET.fromstring('<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>')
>>> root.xpath('.//Variable[@name="A0"]')[0].attrib['value']='test'
>>> print ET.tostring(root,pretty_print=True)
<TopoDefs>
  <Device Name="SNB" LogicalType="CORE" IdCode="0x03886A21" Mask="0xf0000000">
    <Variable name="A0" value="test" 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>

或者您可以循环浏览Variables并根据我的理解更改所有值:

>>> for i in root.xpath('.//Variable'):
...     i.attrib['value']='CHANGE'
...     
>>> print ET.tostring(root,pretty_print=True)
<TopoDefs>
  <Device Name="SNB" LogicalType="CORE" IdCode="0x03886A21" Mask="0xf0000000">
    <Variable name="A0" value="CHANGE" type="GREEN"/>
    <Variable name="A1" value="CHANGE" type="GREEN"/>
    <Variable name="A2" value="CHANGE" type="GREEN"/>
    <Variable name="A3" value="CHANGE" type="GREEN"/>
    <Variable name="B0" value="CHANGE" type="BLUE"/>
    <Variable name="B1" value="CHANGE" type="BLUE"/>
    <Variable name="B2" value="CHANGE" type="BLUE"/>
    <Variable name="B3" value="CHANGE" type="BLUE"/>
  </Device>
</TopoDefs>