python - XML 解析不显示节点
问题描述
from xml.etree import ElementTree
t = """<collection xmlns:y="http://tail-f.com/ns/rest">
<appliance xmlns="http://networks.com/vnms/nms">
<uuid>088fbb70-40d1-4aaf-8ea3-590fd8238828</uuid>
<name>SRVDHCPE1</name>
<num-cpus>0</num-cpus>
<memory-size>0</memory-size>
<num-nics>4</num-nics>
</appliance>
<appliance xmlns="http://networks.com/vnms/nms">
<uuid>088fbb70-40d1-4aaf-8ea3-590fd8238828</uuid>
<name>SRVDHCPE2</name>
<num-cpus>0</num-cpus>
<memory-size>0</memory-size>
<num-nics>4</num-nics>
</appliance>
</collection>"""
dom = ElementTree.fromstring(t)
for n in dom.findall("collection/appliance/name"):
print(n.text)
寻找所有的名字,但它没有显示。我在这里做错了什么。
解决方案
您的案例肯定与Parsing XML with Namespaces相关:
dom = ET.fromstring(t)
ns = {'rest': 'http://tail-f.com/ns/rest','nms': 'http://versa-networks.com/vnms/nms'}
for n in dom.findall("nms:appliance/nms:name", ns):
print(n.text)
输出:
SRVDHCPE1
SRVDHCPE2
推荐阅读
- unity3d - 为什么计算着色器可能会从未更改的数据中随机产生不同的结果?
- c++ - 拖放不同的项目文本
- c# - 我正在使用一系列 if/else 语句,但不是让我在运行时“通过”它们,而是直接进入最后一个 else 语句
- firebase - 当一个流依赖于另一个流时,如何在颤动中拥有多个应用程序流?
- node.js - 创建新对象时,猫鼬中的值不会增加
- google-chrome - 如何在 Linux 的 Windows 子系统上开发 Flutter Web 应用程序(Debian 10)
- python - 在 Python 3 中创建一个单词翻译应用程序。任何“最佳实践”?
- reactjs - 如何将悬停选择器添加到样式对象?
- python - if 块的第一个条件被跳过
- awk - awk比lz4解压慢