首页 > 解决方案 > 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)

寻找所有的名字,但它没有显示。我在这里做错了什么。

标签: pythonxml-parsingelementtree

解决方案


您的案例肯定与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

推荐阅读