1

For this xml

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

I'm trying to print the Name for each Location

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)

1 Answers1

1
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)

I don't think you need to go about writing a file first before parsing it? My solution shows one possible solution, and I'm sure there are many.

Short explanation: The decoding part makes the binary "string" a string that can be used by ET. In the findall-part, I had to include the "." for the search to start from the root element, and the "//" includes all relative nodes at all depths. Also, the default namespace had to be included. Hope this helps.

Zug_Bug
  • 186
  • 10
  • Thanks @Zug_Bug. These are my first steps in python, and I greatly appreciate your help. I now see that I need to include the default namespace and how to properly specify the nodes I want. The reason i downloaded the xml first is because if I do it with a request from the web, I get this encoding error (which I'm getting with your exact same code): UnicodeEncodeError: 'ascii' codec can't encode character u'\xa9' in position 229: ordinal not in range(128) ...... Any ideas? – Rodrigo Barreiro Oct 12 '19 at 07:46
  • Nevermind, figured it out. Seems like the decoding part is needed in Windows, but not on Mac or Linux platforms (https://stackoverflow.com/questions/12349728/elementtree-and-unicode) – Rodrigo Barreiro Oct 12 '19 at 07:54