3

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?

Bruce
  • 33,927
  • 76
  • 174
  • 262
  • 1
    Step 1 search. Python has several XML parsers already in the standard library. http://docs.python.org/library/markup.html What part of the standard library documentation is hard to read? Please choose one of the existing XML parsers, and follow the examples. When you get stuck, please ask a **specific** question about the parser your chose. – S.Lott Jan 24 '12 at 10:45
  • That's a stilly question. There are several. They have different purposes. I've used them all. Please **Read** the documentation first before asking silly questions. – S.Lott Jan 24 '12 at 10:48
  • 1
    Please have a look at this [link](http://www.blog.pythonlibrary.org/2010/11/12/python-parsing-xml-with-minidom/). It should be simple and clear. – Frankline Jan 24 '12 at 10:49
  • @Bruce: Clearly. And I resent that. There's a lot to learn, and you need to actually learn it yourself. – S.Lott Jan 24 '12 at 11:24
  • possible duplicate of [Really simple way to deal with XML in Python?](http://stackoverflow.com/questions/3106480/really-simple-way-to-deal-with-xml-in-python) – phihag Jan 24 '12 at 11:25

2 Answers2

4

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

Shriram
  • 155
  • 1
  • 3
  • 15
Bruce
  • 33,927
  • 76
  • 174
  • 262
4

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')]
Joao Figueiredo
  • 3,120
  • 3
  • 31
  • 40