首页 > 解决方案 > 打印xml节点python xtree

问题描述

对于这个 xml

http://dev.virtualearth.net/REST/v1/Locations?q=St%20Mard,%20FR&o=xml&key= {BingMapsKey}

我正在尝试打印每个位置的名称

import requests
import xml.etree.ElementTree as ET

url = 'http://dev.virtualearth.net/REST/v1/Locations?q=St%20Mard,%20FR&o=xml&key={BingMapsKey}'

response = requests.get(url)
with open('loc.xml', 'wb') as file:
    file.write(response.content)

mytree = ET.parse('/Users/xxxxxxx/Desktop/pscripts/loc.xml')

name = mytree.findall('Name')

for n in name:

    n = name.text
    print (n)

标签: pythonxmlelementtree

解决方案


import requests
import xml.etree.ElementTree as ET

url = 'http://dev.virtualearth.net/REST/v1/Locations?q=St%20Mard,%20FR&o=xml&key={BingMapsKey}  '

response = requests.get(url).content.decode("utf-8-sig")

mytree = ET.fromstring(response)

name = mytree.findall('.//{http://schemas.microsoft.com/search/local/ws/rest/v1}Name')

for n in name:
    print (n.text)

我认为您不需要在解析文件之前先编写文件吗?我的解决方案显示了一种可能的解决方案,我相信有很多。

简短说明:解码部分使二进制“字符串”成为 ET 可以使用的字符串。在 findall-part 中,我必须包含“。” 搜索从根元素开始,“//”包括所有深度的所有相关节点。此外,还必须包含默认命名空间。希望这可以帮助。


推荐阅读