我正在尝试将每个元素<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'))
我如何收集这些数据?
1条答案
按热度按时间ztigrdn81#
你可以使用Python中的xml.etree.ElementTree模块来解析XML字符串并提取所需的信息,下面是一个例子来说明你是如何做到这一点的:
这将从XML中提取所有
sequence-number
标记,并将其文本存储在result
列表中。请注意,这假定XML字符串格式正确,并且
sequence-number
标记嵌套正确。如果XML格式不正确或标记嵌套不正确,则可能需要使用其他逻辑来处理这些情况。我从www.example.com得到了答案openai.com