Unit1
Unit1

Reputation: 95

Python XML etree - How to read node value inside a value?

My task is to output a collection of hardware information (CPU, Motherboard, Memory...) from the system, that ran the python script.

I have exported via a python script the entire system specs using hlsw on a linux system. My goal is to read the values of certain XML nodes (not the text but the node values of these types of XML nodes).

The XML file is as follows:

<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>

And I connect to it via 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"

In my experience neither text nor attribute seemed to be able to read the value inside the value inside the setting node. How can I read the value of setting 'ip'?

Upvotes: 0

Views: 2222

Answers (1)

tboz203
tboz203

Reputation: 474

Is this what you're looking for?

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

gives output:

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

Upvotes: 2

Related Questions