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>

我完全是python脚本的新手。如何解析 xml 文件并指向属性值以替换为将一直更改的新值?如果我使用 getElementsByTagName 和 nodevalue,它将读取节点的所有字符串,我如何通过仅读取值来限制并且其他变量保持不变?

4

1 回答 1

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)
于 2012-10-16T08:59:05.017 回答