python - 打印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)
解决方案
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 中,我必须包含“。” 搜索从根元素开始,“//”包括所有深度的所有相关节点。此外,还必须包含默认命名空间。希望这可以帮助。
推荐阅读
- powershell - 使用 StreamReader 在每行的多个列上复制 Vlookup 的问题
- bash - 尝试使用 awk 解析 DNS 区域文件,但在将前导字符与 awk 匹配时遇到问题
- javascript - 如何创建 JavaScript 对象并动态填充数据?
- django - 无法使用 django 限制对帖子编辑屏幕的访问
- python - 单击已打开网页上的按钮
- node.js - 用户重新排序资源的 RESTful 解决方案
- python - 类型错误:生产()得到了一个意外的关键字参数“linger_ms”
- qt - 在 Go 中运行简单的 Qt GUI 应用程序
- javascript - html 后端的类模型
- java - ClassCastException Processing.core