Python XML etree - 如何读取值内的节点值?

时间:2017-05-17 13:03:42

标签: python xml elementtree

我的任务是从运行python脚本的系统输出一组硬件信息(CPU,主板,内存......)。

我已经在Linux系统上使用hlsw通过python脚本导出了整个系统规范。我的目标是读取某些XML节点的值(不是文本,而是这些类型的XML节点的节点值)。

XML文件如下:

<parent>
    <child>
        <node handle="PCI:0000:02:00.0" class="network" claimed="true" id="network:0">
            <description>Ethernet interface</description>
            <product>I350 Gigabit Network Connection</product>
            <vendor>Intel Corporation</vendor>
            <physid>0</physid>
            <businfo>pci@0000:02:00.0</businfo>
            <logicalname>eth1</logicalname>
            <version>01</version>
            <serial>0c:14:7h:d9:4t:30</serial>
            <size units="bit/s">100000000</size>
            <capacity>1000000000</capacity>
            <width units="bits">32</width>
            <clock units="Hz">33000000</clock>
                 <configuration>
                 <setting id="autonegotiation" value="on"/>
                 <setting id="broadcast" value="yes"/>
                 <setting id="driver" value="igb"/>
                 <setting id="driverversion" value="5.3.0-k"/>
                 <setting id="duplex" value="full"/>
                 <setting id="firmware" value="1.63, 0x800009fa"/>
                 <setting id="ip" value="192.168.2.15"/>
                 </configuration>
        </node>
    </child>
    <child>
        <node>
            <description>Ethernet interface 2</description>
            <logicalname>eth2</logicalname>
                  <configuration>
                      <setting id="ip" value="172.24.2.16"/>
                  </configuration>
        </node>
    </child>
</parent>

我通过Element Tree连接到它:

import xml.etree.ElementTree as ET
tree = ET.parse('specs.xml')
treeRoot = tree.getroot()

for node in treeRoot.findall(".//child"):
    info=node.find("node/logicalname")
    if hasattr(info, 'text'):
        print info.text + " <--- Logical Name"
    info=node.find("node/configuration/setting[@id='ip']")
    if hasattr(info, 'text'):
        print info.text + " <--- IP address"

根据我的经验,文本和属性似乎都无法读取设置节点内值的值。如何阅读设置&#39; ip&#39;?

的价值

1 个答案:

答案 0 :(得分:1)

这是你要找的吗?

print(tree.find('.//node/configuration/setting[@id="ip"]').attrib)

给出输出:

{'value': '192.168.2.15', 'id': 'ip'}