2017-05-17 9 views
0

私の仕事は、pythonスクリプトを実行したシステムからハードウェア情報(CPU、マザーボード、メモリなど)のコレクションを出力することです。Python XML etree - 値の中のノード値を読み取るには?

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>[email protected]: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> 

そして、私は要素ツリーを介して接続:

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" 

私の経験ではテキストも属性が内部値を読み取ることができるように見えました設定ノード内の値どのように私は 'ip'の設定の価値を読むことができますか?

答えて

1

これはあなたが探しているものですか?

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

は出力が得られます。

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

種類のが、私はIPアドレスの値そのものを得ることに興味を持っています、つまり192.168.2.15 – Unit1

+0

'attrib'は辞書オブジェクトであるので、あなたはできるはずです単に '...')。attrib ['value'] '' '192.168.2.15 ''を得る。 – tboz203

+0

ありがとうございます。私は部分文字列(あなたが提供した出力)を使って私が得たものを手に入れましたが、この方法もうまくいくはずです。ロックオン! – Unit1

関連する問題