0

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

M_A
  • 11
  • 4
  • Did you read https://docs.python.org/3/library/xml.etree.elementtree.html#parsing-xml-with-namespaces? – mzjn Jan 30 '21 at 05:51
  • I am not well versed with Python XML parser. However, as part of the standard DOM, there are methods, getElementsByTagName and getElementsByTageNameNS. The first one takes the local name of the element e.g. 'interfaces', the second takes namespace URI as one of the arguments. I am sure Python would have the same, you could explore that. It is essentially looks like namespace issue. – Ironluca Jan 30 '21 at 06:44
  • Thanks @mzjn and Ironluca. I could solve the issue. – M_A Jan 30 '21 at 17:46

1 Answers1

0

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

M_A
  • 11
  • 4