0

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

<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 有什么区别?

4

1 回答 1

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>
于 2012-10-17T17:02:06.587 回答