从 xml 中提取特定的 xml 子项,从变量存储为字节数据类型到 python3 中的列表中

Extract specific xml child items from xml stored as byte datatype from a variable into a list in python3

我正在编写一个 python 脚本,它希望将字节格式的输出值保存到一个变量中。有两个嵌套 for 循环。第一个 for 循环收集租户的名称并将其放入函数中以获取其中的命名空间列表。此命名空间列表是一个 XML 文件,并以字节数据类型输出。

示例如下:

Source = b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><namespaces><name>Namespacename1</name><name>Namespacename2</name>'

import lxml
from xml.etree import ElementTree as ET

for tenant in tenants:
    c.GET('/mapi/tenants/'+tenant+'/namespaces')#This comes from another sdk so ignore this
    c.response_status # this also is part of the sdk so ignore this
    source = c.read() # This operation is also part of the sdk so ignore this as well
    print(source)
    nslist = et.fromstring(source)

重点是,我需要从每个 xml 输出(格式为 "bytes")中获取许多名为 'name' 的子项,这些子项存储在名为source 和每个 'name' 值都必须附加到新的列表变量中。

一些 xml 响应是空的,当我尝试遍历每个响应以执行此操作时,我不断收到 xml 解析错误。我尝试了 if else 条件来尝试忽略它。那也失败了!

我大量阅读了 xml.etree 文档,还测试了几个 for 循环。不幸的是,没有任何帮助。 有人可以帮我整理一下吗?

我自己想出了问题的答案。我只是使用枚举选项来解决这个问题。

如我的示例中所述。我有一个字节格式的变量,其中包含一个 xml 文件。我需要 xml 文件中名为 name 的子项。我使用了名为 lxml 的开源模块。您还可以使用 python3 中内置的 xml 模块(ElementTree)。

下面是解决方法。我有一个名为 source 的变量。

source = b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>.<namespaces><name>Building</name><name>Active</name><name>system</name></namespaces>'

nsinfo = nslist.findall('name')
    for q, value in enumerate(nsinfo):
        nsname = str(value.text)
        print(nsname)

Building
Active
System

这将为您提供您要查找的 xml 文件中的特定值。问题解决了!。

你可以看看下面的内容link,以便更好地理解。

https://github.com/Solitarystate/Hitachi-Content-Platform-Capacity-Reporting/blob/master/hcpcapacityreporting_xml.py