python - 打印 xml 节点 python xtree

标签 python xml elementtree

对于这个 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)

最佳答案

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 部分中,我必须包含“.”。从根元素开始搜索,“//”包括所有深度的所有相关节点。此外,必须包含默认 namespace 。希望这会有所帮助。

关于python - 打印 xml 节点 python xtree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58330288/

相关文章:

python - Keras - .flow_from_directory(目录)

python - 为什么softmax分类器梯度除以批量大小(CS231n)?

xml - 使用 PEM 证书在 Powershell 中验证 XML 签名

Python XML 解析器无法获取所有文本

python - 使用 Python/Elementtree 将具有相同标签的多个子元素添加到 en XML 树中

python - gunicorn_django 错误 "cannot find myproject.settings in your PYTHONPATH"

python - .pyw 在启动时通过注册表启动并退出,但通过双击启动有效...?

php - 调用未定义函数 xml_parser_create()

html - 在 web 中播放 xml 文件中给出的视频

python-xml : Not well-formed (invalid token) - xml. etree utf模式