簡體   English   中英

使用命名空間解析 xml

[英]Parsing xml with namespaces

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 . (這里我只粘貼了我的 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

我是這樣解決的:

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的命名空間相關信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM