Skip to content

Python XML Parsing Error Fix

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about Python XML Parsing Error Fix. We cover key concepts, practical examples, and best practices.

Python XML parsers raise errors like "xml.etree.ElementTree.ParseError: mismatched tag", "undefined entity", or "not well-formed" when the XML is malformed, contains unsupported entities, or has invalid characters.

The Problem

import xml.etree.ElementTree as ET

tree = ET.parse('config.xml')

Error:

xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 5, column 10

Wrong Code

# WRONG — no error handling, assumes valid XML
import xml.etree.ElementTree as ET

tree = ET.parse('config.xml')
root = tree.getroot()
print(root.find('database/host').text)

Right Code

import xml.etree.ElementTree as ET

try:
    tree = ET.parse('config.xml')
    root = tree.getroot()
    host = root.find('.//host')
    print(host.text if host is not None else 'Not found')
except ET.ParseError as e:
    print(f"XML parsing error: {e}")

Expected output:

localhost

Step-by-Step Fix

Step 1: Validate XML syntax

python3 -c "import xml.etree.ElementTree as ET; ET.parse('config.xml'); print('Valid XML')"

Step 2: Fix common XML issues

<!-- WRONG — unclosed tag -->
<root>
  <item>
    <name>Example

<!-- RIGHT — properly closed -->
<root>
  <item>
    <name>Example</name>
  </item>
</root>

Step 3: Handle undefined entities

from xml.etree.ElementTree import HTMLParser

# For HTML entities like &nbsp;, &amp;
parser = HTMLParser()
tree = ET.parse('config.xml', parser=parser)

Step 4: Use lxml for better error messages

from lxml import etree

try:
    tree = etree.parse('config.xml')
    root = tree.getroot()
except etree.XMLSyntaxError as e:
    print(f"Line {e.lineno}: {e.message}")

Step 5: Strip invalid characters

import re
import xml.etree.ElementTree as ET

def clean_xml(content):
    invalid = re.compile(r'[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD]')
    return invalid.sub('', content)

with open('data.xml', 'r', encoding='utf-8') as f:
    content = clean_xml(f.read())

root = ET.fromstring(content)

Step 6: Parse from string safely

import xml.etree.ElementTree as ET

xml_string = """<?xml version="1.0"?>
<root>
    <item id="1">Value</item>
</root>"""

root = ET.fromstring(xml_string)
print(root.find('.//item').text)

Prevention Tips

  • Validate XML with a schema (XSD) before processing
  • Use lxml for production parsing — better error messages and features
  • Handle Exception broadly when parsing untrusted XML
  • Use defusedxml to prevent XML external entity (XXE) attacks
  • Always close tags and quote attributes

Common Mistakes with xml parse

  1. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  2. Using return to exit a function early instead of wrapping a pure value in the monad
  3. Mixing let bindings with <- bindings in do notation, producing type errors

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between ElementTree and lxml?

ElementTree is in Python's standard library. lxml is a third-party library that supports XSLT, XPath, schema validation, and has better error messages. For simple parsing, ElementTree suffices. For complex XML processing, use lxml.

How do I protect against XML external entity (XXE) attacks?

Use defusedxml library: import defusedxml.ElementTree as ET; ET.parse('file.xml'). It blocks entity expansion, external entities, and billion laughs attacks. Never parse untrusted XML without protection.

Why does my XML parsing fail with "undefined entity"?

XML supports only 5 predefined entities: &lt;, &gt;, &amp;, &quot;, &apos;. HTML entities like &nbsp; or &mdash; are not defined in XML. Use &amp;nbsp; or define them in the DTD. For HTML content, use HTMLParser.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro