Bruce
Bruce

Reputation: 35285

How to parse an XML file using Python?

I am trying to print all the elements and attributes in an xml file. The xml file's contents are:

<topology>
<switch id="10">
    <port no="1">h1</port>
    <port no="2">h2</port>
</switch>

<tunnel id="91">
<port no="1">s1</port>
<port no="8">s8</port>
</tunnel>
</topology>

How do I do it? Also, how do I search for an element like switch inside topology?

Upvotes: 3

Views: 11335

Answers (2)

Bruce
Bruce

Reputation: 35285

Here is my working code:

import xml.etree.ElementTree as ET

doc = ET.parse("nm.xml")
s = doc.find("switch")
print s.attrib["id"]
for item in s:
  print item.attrib["no"]
  print item.text

t = doc.find("tunnel")
print t.attrib["dpid"]
for item in t:
  print item.attrib["no"]
  print item.text  

P.S: You can replace ET.parse with ET.fromstring and change input argument to a string type It works

Upvotes: 4

Joao Figueiredo
Joao Figueiredo

Reputation: 3188

Like S.Lott expressed, you have way too many ways to skin this cat,

here is an example using lxml,

from lxml import etree

xml_snippet = '''<topology>
 <switch id="10">
     <port no="1">h1</port>
     <port no="2">h2</port>
 </switch>

 <tunnel dpid="91">
 <port no="1">s1</port>
 <port no="8">s8</port>
 </tunnel>
 </topology>'''

root = etree.fromstring(xml_snippet)

for element in root.iter("*"):
  print element.tag, element.items()

output:

topology []
switch [('id', '10')]
port [('no', '1')]
port [('no', '2')]
tunnel [('dpid', '91')]
port [('no', '1')]
port [('no', '8')]

Using XPath to find an attribute

attribute = '10'
element = root.find('.//switch[@id="%s"]' % attribute)
element.items()

output:

[('id', '10')]

Upvotes: 4

Related Questions