我有一个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>
我完全是python脚本的新学习者。如何解析xml文件并指向属性值替换为将一直更改的新值? 如果我使用getElementsByTagName和nodevalue,它将读取节点的所有字符串,如何通过仅读取值来限制,其他变量保持不变?
答案 0 :(得分: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)