python 解析xml以查找每个不起作用的特定标记的文本

bogh5gae  于 2022-12-17  发布在  Python
关注(0)|答案(1)|浏览(135)

我正在尝试将每个元素<sequence-number> text聚集到一个列表中。

#!/usr/bin/env python

from lxml import etree 

response = '''
<rpc-reply xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="urn:uuid:0d07cdf5-c8e5-45d9-89d1-92467ffd7fe4">
 <data>
  <ipv4-acl-and-prefix-list xmlns="http://cisco.com/ns/yang/Cisco-IOS-XR-ipv4-acl-cfg">
   <accesses>
    <access>
     <access-list-name>TESTTEST</access-list-name>
     <access-list-entries>
      <access-list-entry>
       <sequence-number>1</sequence-number>
       <remark>TEST</remark>
       <sequence-str>1</sequence-str>
      </access-list-entry>
      <access-list-entry>
       <sequence-number>10</sequence-number>
       <grant>permit</grant>
       <source-network>
        <source-address>10.10.5.0</source-address>
        <source-wild-card-bits>0.0.0.255</source-wild-card-bits>
       </source-network>
       <next-hop>
        <next-hop-type>regular-next-hop</next-hop-type>
        <next-hop-1>
         <next-hop>10.10.5.2</next-hop>
         <vrf-name>SANE</vrf-name>
        </next-hop-1>
       </next-hop>
       <sequence-str>10</sequence-str>
      </access-list-entry>
      <access-list-entry>
       <sequence-number>20</sequence-number>
       <grant>permit</grant>
       <source-network>
        <source-address>10.10.6.0</source-address>
        <source-wild-card-bits>0.0.0.255</source-wild-card-bits>
       </source-network>
       <next-hop>
        <next-hop-type>regular-next-hop</next-hop-type>
        <next-hop-1>
         <next-hop>10.10.6.2</next-hop>
         <vrf-name>VRFNAME</vrf-name>
        </next-hop-1>
       </next-hop>
       <sequence-str>20</sequence-str>
      </access-list-entry>
     </access-list-entries>
    </access>
   </accesses>
  </ipv4-acl-and-prefix-list>
 </data>
</rpc-reply>
'''
q = etree.fromstring(response)
print(q.findall('.//sequence-number'))

但是没有得到任何输出。我也试过下面的语句,但没有运气:

print(q.findall('./sequence-number/'))
print(q.findall('sequence-number/'))
print(q.findall('.//sequence-number/'))
print(q.findall('sequence-number'))

我如何收集这些数据?

ztigrdn8

ztigrdn81#

你可以使用Python中的xml.etree.ElementTree模块来解析XML字符串并提取所需的信息,下面是一个例子来说明你是如何做到这一点的:

import xml.etree.ElementTree as ET

# Parse the XML string
root = ET.fromstring(xml_string)

# Find all elements with the tag 'sequence-number'
sequence_numbers = root.findall('.//sequence-number')

# Extract the text from each element and add it to the list
result = [number.text for number in sequence_numbers]

这将从XML中提取所有sequence-number标记,并将其文本存储在result列表中。
请注意,这假定XML字符串格式正确,并且sequence-number标记嵌套正确。如果XML格式不正确或标记嵌套不正确,则可能需要使用其他逻辑来处理这些情况。
我从www.example.com得到了答案openai.com

相关问题