Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse an XML file using Python?

Tags:

python

xml

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?

like image 683
Bruce Avatar asked Nov 26 '25 19:11

Bruce


1 Answers

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')]
like image 161
Joao Figueiredo Avatar answered Nov 29 '25 20:11

Joao Figueiredo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!