XML解析不显示节点

时间:2019-07-01 11:06:53

标签: python xml-parsing elementtree

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)

正在查找所有名称,但不会显示。我在这里做错什么了。

2 个答案:

答案 0 :(得分:1)

您的情况肯定与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

答案 1 :(得分:0)

您需要为选择器命名空间:

from xml.etree import ElementTree
from xml.etree.ElementTree import Element

t = """<collection xmlns:y="http://tail-f.com/ns/rest">
  <appliance xmlns="http://versa-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://versa-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>"""

if __name__ == '__main__':
    dom: Element = ElementTree.fromstring(t)
    namespaces = {'n': 'http://versa-networks.com/vnms/nms'}
    for name in dom.findall("./n:appliance/n:name", namespaces=namespaces):
        print(name.text)

打印:

SRVDHCPE1
SRVDHCPE2

供参考:
https://docs.python.org/3.7/library/xml.etree.elementtree.html#parsing-xml-with-namespaces