首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XML解析不显示节点。

XML解析不显示节点。
EN

Stack Overflow用户
提问于 2019-07-01 11:06:53
回答 2查看 23关注 0票数 0
代码语言:javascript
复制
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)

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-07-01 11:23:32

您需要命名您的选择器:

代码语言:javascript
复制
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)

其中的指纹:

代码语言:javascript
复制
SRVDHCPE1
SRVDHCPE2

供参考:

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

票数 0
EN

Stack Overflow用户

发布于 2019-07-01 11:24:48

你的案子绝对与https://docs.python.org/3/library/xml.etree.elementtree.html#parsing-xml-with-namespaces有关

代码语言:javascript
复制
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)

产出:

代码语言:javascript
复制
SRVDHCPE1
SRVDHCPE2
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56834605

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档