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?

5
  • 1
    Step 1 search. Python has several XML parsers already in the standard library. 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. Commented Jan 24, 2012 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. Commented Jan 24, 2012 at 10:48
  • 1
    Please have a look at this link. It should be simple and clear. Commented Jan 24, 2012 at 10:49
  • @Bruce: Clearly. And I resent that. There's a lot to learn, and you need to actually learn it yourself. Commented Jan 24, 2012 at 11:24
  • possible duplicate of Really simple way to deal with XML in Python? Commented Jan 24, 2012 at 11:25

2 Answers 2

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')]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.