I've got an XML file that looks like this:

<routingTable>
    <router>
        <id>1</id>
        <ip>1.1.1.1</ip>
        <nexthop>1.1.1.2</nexthop>
    </router>
    <router>
        <id>2</id>
        <ip>2.2.2.1</ip>
        <nexthop>2.2.2.2</nexthop>
    </router>
</routingTable>

With possibly more than two router entries as time goes on. What I would like to do, is take each router instance and throw it into a dictionary. This way, I can query each one by ID, IP, or nexthop. I've been playing with xml.etree.ElementTree but no luck so far. Tried different things with forloops which will print each of the tag values, but I cant really reference them later. ie:

from xml.etree import ElementTree as ET

routetable = ET.parse('RoutingTable.xml')

for route in routetable.iter():
    print route.text

Recommended Answers

All 2 Replies

I only use BeautifulSoup or lxml,because they are by far the two best parser for python.
Can show you on way with BeautifulSoup.
soup.find_all('router') find all ruter tag,i take out router 1 router_tag[0]
Then put id and ip text in a dictionary.

from bs4 import BeautifulSoup

xml_file = """\
<routingTable>
    <router>
        <id>1</id>
        <ip>1.1.1.1</ip>
        <nexthop>1.1.1.2</nexthop>
    </router>
    <router>
        <id>2</id>
        <ip>2.2.2.1</ip>
        <nexthop>2.2.2.2</nexthop>
    </router>
</routingTable>"""

router1_dict = {}
soup = BeautifulSoup(xml_file, 'xml')
router_tag = soup.find_all('router')
router_1 = router_tag[0]
router1_dict[router_1.find('id').text] = router_1.find('ip').text
print router1_dict #--> {u'1': u'1.1.1.1'}
commented: thanks +13

Thanks. This worked quite well. I changed so that it could open an xml file. And changed the structure of the the dictionary. So:

soup = BeautifulSoup(open("file.xml"), 'xml')



router1_dict = {'id' : router_1.find('id').text, 'ip' : router_1.find('ip').text, 'nexthop' : router_1.find('nexthop').text }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.