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 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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With