1

I try my best to parse an xml string, but it returns an empty list when searching for child elements. I can provide a working python fiddle:

https://onlinegdb.com/SytNQIOcS

but it comes down to this:

root = ET.fromstring(xml_string)
print(root.findall('Race'))

Any tips? Looks like a beginner mistake..

1
  • Element.findall() finds only elements with a tag which are direct children of the current element. Commented Oct 31, 2019 at 12:34

1 Answer 1

1
root = ET.fromstring(xml_string)
namespace = {'ns': 'http://ergast.com/mrd/1.4' }

for race in root.find('ns:RaceTable', namespace):
    round_num = race.get("round")
    circuit = race.find('ns:RaceName', namespace).text
    date = race.find("ns:Date", namespace).text
    time = race.find("ns:Time", namespace).text
    print(round_num, circuit, date, time)

Errors:

  1. Element.findall() finds only elements with a tag which are direct children of the current element.
  2. If the XML input has namespaces, tags and attributes with prefixes in the form prefix:sometag get expanded to {uri}sometag where the prefix is replaced by the full URI. Also, if there is a default namespace, that full URI gets prepended to all of the non-prefixed tags. Checkout this documentation https://docs.python.org/2/library/xml.etree.elementtree.html#parsing-xml-with-namespaces

You can use something like this

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.