使用命名空间解析 xml

时间:2021-01-30 04:38:24

标签: python-3.x xml netconf

我正在使用 xml.etree.ElementTree 解析 XML 文件,我正在读取 xml,但是当它运行时,我无法获取信息,因为 rpc-reply 和 interfaces 行具有 message- idxmlns。 (这里我只粘贴我的 xml 的一部分)。所以,如果我手动删除 message-id xxxxmlns xxx 我可以解析 xml,否则我无法获取信息。我应该将什么添加到我的 python 代码中?并正确获取信息。这个想法不是手动删除我评论的行。

<?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>

我的python代码是:


    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 个答案:

答案 0 :(得分:0)

我是这样解决的:

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

我使用了来自 https://docs.python.org/3/library/xml.etree.elementtree.html

的与命名空间相关的信息
相关问题