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

Dani AI

Generated

Good, simple solution from and a sensible file-based tweak by . For a general, reusable approach that works for any number of <router> entries, parse each <router> into a dict-of-dicts keyed by its ID and build small reverse indexes for fast lookups by IP or nexthop. ElementTree is fine for well-formed XML; lxml or xmltodict are alternatives when namespaces or full dict conversion are needed.

import xml.etree.ElementTree as ET
from collections import defaultdict

def load_routes(path):
    tree = ET.parse(path)
    root = tree.getroot()
    routes = {}
    by_ip = {}
    by_nexthop = defaultdict(list)
    for router in root.findall('router'):
        rid = (router.findtext('id') or '').strip()
        if not rid:
            continue
        ip = (router.findtext('ip') or '').strip()
        nh = (router.findtext('nexthop') or '').strip()
        routes[rid] = {'id': rid, 'ip': ip, 'nexthop': nh}
        if ip: by_ip[ip] = rid
        if nh: by_nexthop[nh].append(rid)
    return routes, by_ip, by_nexthop

Example usage: call load_routes('RoutingTable.xml') to get routes (lookup by id), by_ip (map ip→id), and by_nexthop (nexthop→[ids]). For very large files, use ET.iterparse() and elem.clear() to stream and free memory:

def stream_load(path):
    routes = {}
    for _, elem in ET.iterparse(path, events=('end',)):
        if elem.tag == 'router':
            rid = (elem.findtext('id') or '').strip()
            routes[rid] = {
                'id': rid,
                'ip': (elem.findtext('ip') or '').strip(),
                'nexthop': (elem.findtext('nexthop') or '').strip()
            }
            elem.clear()
    return routes

Notes: handle missing tags with findtext(..., ''), trim whitespace, convert numeric IDs with int() guarded by try/except, and consider ipaddress for IP validation. If IDs may repeat, store lists instead of single entries. BeautifulSoup is convenient for quick hacks (as shown by ), but for production use prefer ElementTree/lxml or xmltodict for clearer structure and better performance.

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.