'Parsing XML with python ElementTree: ParseError: mismatched tag

I have several XML files I have to parse through with python ElemetTree (they are legacy from another developer).

I've corrected those files a bit and parsed a good chunk so far but at some moment I got this parsing error, and I can't get around it. Tried parsing the original file (i was working with a copy ofcourse), and it's still the same error even though it used to work fine in the first place.

Error: ParseError: mismatched tag

My code is:

import xml.etree.ElementTree as ET
tree = ET.parse('astrod.xml')

Full error text:

Traceback (most recent call last):

  File "D:\dev\tools\Anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-4-6aa074179306>", line 2, in <module>
    tree = ET.parse('astrod.xml')

  File "D:\dev\tools\Anaconda\lib\xml\etree\ElementTree.py", line 1197, in parse
    tree.parse(source, parser)

  File "D:\dev\tools\Anaconda\lib\xml\etree\ElementTree.py", line 598, in parse
    self._root = parser._parse_whole(source)

  File "<string>", line unknown
ParseError: mismatched tag: line 449, column 3


Solution 1:[1]

Take a look at line ParseError: mismatched tag: line 449, column 3.

line 449 is the line number in your source XML file. Find this line and look what is wrong with the content. Probably this line contains some tag (e.g. closing) which has no opening conterpart.

An alternative: Visit any XML validation site and check what is wrong with your file.

Solution 2:[2]

I find that sometimes you get this error at a line number a lot later than the actual error. It only notices something wrong when you close a tag that you didn't correctly open. Look earlier in the file.

For example I had a similar problem where the error message claimed

xml.etree.ElementTree.ParseError: mismatched tag: line 12, column 2

but the mistake wasn't at the mentioned line, I had misspelled one tag opening at the beginning.

Check backwards through your input for the opening tag of the one that's given you this error.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Valdi_Bo
Solution 2 AndrewC