Parsing xml with namespaces

440 Views Asked by At

I am parsing a XML file using xml.etree.ElementTree, and I am reading a xml, however when it runs, I can't take the information because the lines rpc-reply and interfaces have the message-id and xmlns. (Here I only paste one part of my xml). So, if I delete manualy the message-id xxx and xmlns xxx I can parse the xml, if not, I can not take the information. Whay should I add to my python code? and take properly the information. The idea is not delete manually the lines that I commented.

<?xml version="1.0"?>
<rpc-reply message-id="urn:uuid:1577eb48-18f7-4818-afde-468fe24382d7" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
 <data>
  <interfaces xmlns="http://openconfig.net/yang/interfaces">
   <interface>
    <name>Loopback102</name>
    <state>
     <name>Loopback102</name>

My python code is:


    for data in root.findall('data'):
       for interfaces in data.findall('interfaces'):
          for interfacen in interfaces.findall('interface'):
             for state in interfacen.findall('state'):
                   inter = state.find('name').text
                   portoperationalstate = state.find('oper-status').text
                   protocol = state.find('admin-status').text
                   info1 = state.find('description').text

1

There are 1 best solutions below

0
On

I solved it this way:

for rpc_reply in root.findall('{urn:ietf:params:xml:ns:netconf:base:1.0}data'):
   for data in rpc_reply.findall('{http://openconfig.net/yang/interfaces}interfaces'):
      for interfaces in data.findall('{http://openconfig.net/yang/interfaces}interface'):
         for interfacen in interfaces.findall('{http://openconfig.net/yang/interfaces}state'):
            inter = interfacen.find('{http://openconfig.net/yang/interfaces}name').text   
            portoperationalstate = interfacen.find('{http://openconfig.net/yang/interfaces}oper-status').text
            protocol = interfacen.find('{http://openconfig.net/yang/interfaces}admin-status').text
            info1 = interfacen.find('{http://openconfig.net/yang/interfaces}description').text

I used info related to namespace from https://docs.python.org/3/library/xml.etree.elementtree.html