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>