XML processing becomes difficult when the document stops looking like a simple configuration file. Namespaces, mixed content, recurring elements, schema validation and unexpected input can change which Python interface makes sense. A dictionary converter and a document tree may both extract an invoice total while preserving very different information.
ElementTree, lxml, xmltodict, Beautiful Soup and defusedxml address different parts of that problem. The right choice depends on the output contract and the trust boundary, rather than a universal ranking. Some can also be combined: a restricted parser can sit beneath a familiar tree API, while a separate validator checks business structure.
Decide what must survive parsing
Begin with the actual exchange format. Data-oriented XML with repeated records often maps naturally into Python collections. Narrative XML with text between child elements requires more care. Namespace prefixes are presentation choices, while namespace URIs carry identity; dropping them can merge fields that mean different things.
Also distinguish well-formedness from validity and business correctness. A parser accepting a document does not establish that its schema is satisfied, its totals reconcile or its sender is authorized. If the downstream payload is JSON, our Python JSON library comparison covers that separate serialization decision.
The quick difference
| Product | Best fit | Strengths, limits and cost |
|---|---|---|
| ElementTree | Small, controlled XML trees | Included with Python; tree editing and incremental parsing. Limited XPath subset and no complete schema-validation stack. |
| lxml | Rich document queries and validation | ElementTree-style API plus XPath, XSLT and validators. Native dependencies and explicit parser/resource policy matter. |
| xmltodict | Record-shaped XML to dictionaries | Convenient parse/unparse and streaming callbacks. Mapping conventions and mixed-content round trips need review. |
| Beautiful Soup | Familiar searches across markup | Search and navigation wrapper; XML mode depends on lxml. HTML recovery rules must not be mistaken for XML semantics. |
| defusedxml | Restricted standard-library parsing | Rejects selected dangerous XML constructs through familiar interfaces. Complements input limits; not a general validator. |
ElementTree
ElementTree is the standard-library starting point for reading, creating and updating XML trees. Elements carry attributes, text and children, and its find-style methods handle many small extraction tasks. It avoids adding a separate Python package just to traverse a controlled feed or generate a modest document.
Its XPath support is deliberately a subset, so a query copied from a full XPath engine may not work. Streaming interfaces such as iterparse can help process repeated records, but memory depends on whether your code releases processed elements and avoids retaining the full tree. Incremental input alone does not prove bounded memory.
Choose it when the document contract is stable and its query model is sufficient. Treat handling of untrusted input as a separate design review: current Python documentation flags XML risks and the relevance of the linked Expat version. Being bundled with Python does not make every configuration or upstream document safe.
lxml
lxml adds a broader XML toolset around libxml2 and libxslt while retaining an ElementTree-like interface. XPath and XSLT are useful when transformations are naturally expressed as document operations. Its validation tools include DTD, Relax NG and XML Schema capabilities, which makes it attractive for formal interchange contracts.
The extra capability brings packaging and resource-access decisions. A suitable wheel can simplify installation, while source builds involve native dependencies. Confirm the supported platform and library versions in the environment that will execute the job, including containers and build agents, rather than assuming a laptop installation settles deployment.
For externally supplied documents, define entity handling, DTD loading and resource resolution explicitly. The documentation also distinguishes parsing resources from access during XSLT transformations. A network restriction on one parser is not a blanket sandbox for every later operation. Use lxml for its standards features, with a documented configuration and bounded inputs.
xmltodict
xmltodict is aimed at making XML data convenient to consume as dictionaries. Its documented defaults use an attribute prefix and a separate text key. The parse and unparse functions make it practical for applications whose real concern is a record structure rather than detailed document editing.
Two decisions deserve early attention. Namespace processing is optional rather than the default, and a field appearing once may need force_list to produce the same collection shape as a repeated field. Define those conventions centrally so one supplier sending a single line item does not change an API type unexpectedly.
The project documents streaming callbacks and entity parsing disabled by default. Those features do not turn every conversion into a lossless round trip. Mixed content, whitespace, comment ordering and nested-list serialization need representative fixtures. Prefer it for stable data-shaped feeds, and keep the original document separately when exact preservation matters.
Beautiful Soup
Beautiful Soup offers a consistent navigation and search interface over markup parsers. Teams already using its tag searches and traversal methods may find it convenient for small extraction tasks. In XML mode, however, its documented supported parser is lxml; it is not an independent replacement XML engine.
Choose XML mode deliberately. Allowing the library to select an installed HTML parser can introduce HTML normalization rules, alter tag handling or produce a different tree for malformed markup. The documentation recommends specifying a parser where reproducible behavior matters. A permissive parse should not silently become acceptance of a broken partner contract.
This option fits extraction code whose maintainers value Beautiful Soup navigation and can accept the additional layer. If the job primarily needs schema validation or XSLT, using lxml directly keeps those responsibilities visible. Avoid describing successful extraction from damaged markup as proof that the input was valid XML.
defusedxml
defusedxml focuses on restricting problematic XML behavior through interfaces resembling standard-library modules. Its documented controls include forbidding DTDs, entities and external references. This is useful when an existing ElementTree-style import path needs a clearer rejection policy for material supplied outside the application.
The controls are distinct. For example, the documented forbid_dtd option should be set according to the application policy rather than assuming every DTD is rejected by every default. Expected exceptions should be translated into an understandable import failure, with diagnostic information that does not expose private document contents.
It is a protective parsing layer, not a replacement for schema validation, authorization or limits on upload and decompression size. The repository also marks its old lxml integration as deprecated, so do not select that as the modern general lxml wrapper. Review the exact module and configuration you intend to use.
An evaluation checklist for XML imports
Create a small fixture collection before settling the interface: one and many repeated records, a default namespace, two namespaces sharing a local name, mixed text, an empty value and malformed input. Add the largest realistically accepted document. Check both extracted values and the shape of the resulting Python objects.
Write down the rejection policy for oversized data, external references and unexpected document structure. Bound processing time and memory in the surrounding application as well as choosing parser options. Keep schema files and transformation resources under explicit control when they are required.
These libraries run within your application, rather than charging per parsed document as a hosted API. Review their distribution licenses and native dependency notices for your release. The practical costs are engineering, packaging, monitoring and supporting the data contract, not a comparable subscription tier.
Which should you choose?
Start with ElementTree for straightforward controlled trees, and move to lxml when document querying, transformation or validation justifies the extra stack. Choose xmltodict when a deliberately defined dictionary mapping is the intended result.
Use Beautiful Soup when its navigation model fits the extraction task and XML mode is explicit. Consider defusedxml for restricted standard-library parsing, alongside current dependencies and application limits. The strongest choice is the one whose preserved information and rejected inputs match your contract.
References
Official product, documentation and licensing sources checked on December 3, 2026. Product fit judgments are editorial analysis; this comparison does not report hands-on benchmark results.
