499 Commits
Author SHA1 Message Date
Jelle van der WaaandStan Ulbrych 2dd5315a76 gh-159675: Tidy and lazify imports in xml.sax.saxutils (#159676)
Co-authored-by: Stan Ulbrych <stan@python.org>
2026-10-19 19:57:20 +01:00
Serhiy Storchaka 9bd9c7461d gh-54092: Implement writexml() for DocumentFragment in xml.dom.minidom (GH-156646)
toxml() and toprettyxml() now work for document fragments.  They write
the children of the fragment, without adding a level of indentation.
2026-09-13 19:04:32 +00:00
Serhiy Storchaka da5a15571c gh-44376: Write missing namespace declarations in xml.dom.minidom (GH-156674)
Element.writexml() now writes the xmlns declarations needed for the
namespaces of the element and its attributes, if they are not already
declared for an ancestor.  A prefix in scope is reused for an attribute
in a namespace without a prefix, or a new one is invented, because
attributes cannot use the default namespace.  The document is not
modified by the serialization.
2026-09-13 20:32:59 +03:00
Serhiy Storchaka ce32912328 gh-61290: Fix serializing attributes with the default_namespace option (GH-156747)
Serialization with the default_namespace option failed for any attribute
without a namespace.  But a default namespace declaration does not apply
to attribute names, so an unqualified attribute name is written as is.
For the same reason a qualified attribute name in the default namespace is
now written with a prefix; it was written without one, which lost its
namespace (gh-113581).
2026-09-13 17:21:03 +00:00
Serhiy Storchaka ad447fa0a3 gh-156665: Validate namespaces in xml.dom.minidom (GH-156666)
createElementNS(), createAttributeNS() and setAttributeNS() now raise
NamespaceErr for a malformed qualified name, for a prefix with an empty
namespace, and for illegal use of the "xml" and "xmlns" prefixes, as required
by DOM Level 2 Core.  Setting the prefix of an attribute is validated too.

Two tests used a wrong namespace URI for xmlns attributes.
2026-09-13 19:43:24 +03:00
Serhiy Storchaka 33083601f5 gh-81623: Do not add whitespace to significant content when pretty-printing (GH-156660)
Pretty-printing added whitespace inside an element which contains text,
which changed its content.  Now xml.dom.minidom.Node.toprettyxml() and
xml.etree.ElementTree.indent() do not add whitespace inside an element
which is marked with xml:space="preserve" or which contains text.
toprettyxml() also takes into account the content model declared in
the DTD: only white space in element content is ignorable.
2026-09-13 18:09:47 +03:00
Serhiy Storchaka a2f4f1913b gh-63102: Support custom targets in the pull parser (GH-156888)
The list of events was collected by the TreeBuilder in the C implementation,
so the pull parser only worked with the standard target.  The parser itself
now collects the events, and reports what the target returns.  XMLPullParser
and iterparse() get the target parameter, which makes it possible to parse a
large document incrementally without building a tree for it.

The namespace events no longer need a separate code path: the parser reports
the prefix and the uri if the target does not implement start_ns()/end_ns(),
as the Python implementation already did.
2026-09-13 13:24:17 +00:00
Serhiy Storchaka f802d2d246 gh-157406: Report all document type declarations in the Python XMLParser (GH-157408)
The Python implementation of XMLParser only reported a document type
declaration with an external identifier.  Use the Expat handler, like
the C implementation does.
2026-09-13 09:05:20 +00:00
Serhiy Storchaka 5056ac552a gh-156797: Escape the namespace URI in xml.sax.saxutils.XMLGenerator (GH-156799)
The namespace declarations were the only attribute values written without
quoteattr(), so a URI containing "&", "<" or a quote character produced a
document which cannot be parsed.
2026-09-03 00:10:23 +03:00
Serhiy Storchaka 09ff4d443f gh-156765: Fix inaccuracies in the ElementTree documentation (GH-156766)
Corrected:

* the parser argument of iterparse() is an instance of XMLParser or its
  subclass, not a subclass;
* feed() accepts a string as well as encoded data;
* keys() and items() do not return a list in the Python implementation, and
  the attributes are no longer returned in an arbitrary order.

Removed the claims that the element tag, the attribute names and values, the
text of a comment and the data of TreeBuilder.data() can be bytes.  It is a
Python 2 leftover.  Documented instead what they can be.
2026-09-02 17:18:32 +00:00
Serhiy Storchaka c2658214da gh-156839: Fix inaccuracies in the xml.dom.pulldom documentation (GH-156840)
Corrected:

* the node types for the PROCESSING_INSTRUCTION and COMMENT events;
* the return value of getEvent() at the end of the document;
* the type of the argument of parseString();
* references to the xml.dom interfaces, written as xml.dom.minidom.

Documented:

* the event constants, which were referenced but never described;
* PullDOM, SAX2DOM and the documentFactory argument;
* the arguments of DOMEventStream, its reset() and clear() methods.

Added docstrings to the module, the classes and their public methods, and
removed the commented out paragraph about pulldom in the xml.dom
documentation, which was never rendered and refers to a site which no longer
exists.
2026-09-02 19:50:58 +03:00
Serhiy Storchaka 6f7941e0aa gh-156829: Fix inaccuracies in the xml.sax documentation (GH-156830)
Corrected:

* the name of the errorHandler argument of parse() and parseString();
* the default value of the parser_list argument of make_parser();
* the description of the source of parse();
* the types of the declaration-handler and dom-node properties;
* the way in which names are interned;
* the description of IncrementalParser.

Documented:

* default_parser_list and SAXReaderNotAvailable;
* property_encoding and property_interning_dict;
* IncrementalParser.prepareParser();
* XMLFilterBase.getParent() and setParent();
* which features and properties the parser based on Expat does not support.

Added missing docstrings to parse(), parseString(), AttributesImpl and
XMLGenerator.
2026-09-02 19:49:18 +03:00
Serhiy Storchaka e7c93b7e5c gh-156658: Only XML white space characters are treated as white space (GH-156659)
XML defines white space as " \t\r\n" (see XML 1.0, 2.3), but str.strip()
also strips other characters, such as U+00A0.  Such characters could be
lost in ElementTree.indent(), in canonicalize(strip_text=True), and when
parsing with the whitespace-in-element-content feature turned off.
2026-09-02 15:30:21 +03:00
Serhiy Storchaka 532b9dbd67 gh-89499: Support the standalone document declaration in ElementTree (GH-156730)
ElementTree.write(), tostring() and tostringlist() get the standalone
parameter: True for standalone="yes", False for standalone="no", and None
(the default) to omit it.  An XML declaration is written if it is not None,
and combining it with a false xml_declaration is an error.
2026-09-01 18:01:47 +03:00
Serhiy StorchakaandJason Orendorff d636e3c028 gh-44871: Improve DOM Level 1 conformance of xml.dom.minidom (#155641)
* The factory methods now raise InvalidCharacterErr if the name is not
  a valid XML name.
* Inserting or setting a node created by another document now raises
  WrongDocumentErr.
* Setting an attribute node which belongs to another element now raises
  InuseAttributeErr.
* Inserting a node into itself or its descendant now raises
  HierarchyRequestErr.
* A document can have only one element child and only one document type
  child, and a document fragment can no longer have notation children.
* Removing an absent attribute now has no effect instead of raising
  NotFoundErr.
* Attributes defaulted in the DTD are no longer omitted when parsing,
  and Attr.specified now reports whether the attribute was given in the
  start tag.  This needs the new pyexpat method
  GetSpecifiedAttributeCount().
* EntityReference nodes and Document.createEntityReference() are now
  implemented.
* The exceptions required by the DOM are now documented, and minidom
  specific differences are described in the minidom documentation.

Co-authored-by: Jason Orendorff <283361+jorendorff@users.noreply.github.com>
2026-08-30 13:27:33 +03:00
8420052846 gh-90756: Fix the ElementTree XML declaration for utf-8-sig (GH-31043)
The BOM already determines the encoding, so the declaration is now
omitted by default, and declares utf-8 if requested explicitly.

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-13 05:50:34 +00:00
Daniel Hillier 87b120fdb5 gh-118318: Remove outdated c14n references from ElementTree (GH-118319)
Some references to a removed `c14n` serialization method remained in
ElementTree.py. Attempting to use `method='c14n'` in the `write()`
method would result in `ValueError: unknown method 'c14n'`.

Removes the `write_c14n()` method that uses `method='c14n'` and also
raises the same error.
2026-08-09 21:06:42 +00:00
2ffab08378 gh-152674: Avoid quadratic behavior in xml.etree.ElementPath index predicates (GH-152676)
Co-authored-by: Alexis <alexis.challande@trailofbits.com>
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
2026-07-28 13:36:47 +02:00
Serhiy Storchaka bcd29e466f gh-149489: Fix ElementTree serialization to HTML (GH-149490)
* The content of comments, processing instructions and elements "xmp",
  "iframe", "noembed", "noframes", and "plaintext" is no longer escaped.
* The "plaintext" element no longer have the closing tag.
* Add support of empty attributes (with value None).
2026-05-30 00:04:50 +03:00
Serhiy Storchaka 01c6d3d76b gh-150285: Fix too long docstrings in some Python modules (GH-150366) 2026-05-25 07:33:54 +00:00
Jelle Zijlstra b45319e132 gh-139489: Add is_valid_text to xml.__all__ (#149641) 2026-05-10 13:43:57 -07:00
Serhiy Storchaka a5c7a74418 gh-139489: Add xml.is_valid_text() (GH-149412) 2026-05-06 14:40:10 +00:00
Serhiy Storchaka a76d9573e4 gh-139489: Add xml.is_valid_name() (GH-139768)
It allows to check whether a string can be used as an element or attribute
name in XML.
2026-05-05 11:25:22 +03:00
Neko Asakura afd8113e9d gh-144270: Make SubElement parent and tag positional-only (GH-144845)
The C accelerator implementations use PyArg_ParseTuple, which
inherently enforces positional-only parameters. The Python fallback
allowed these as keyword arguments, creating a behavioral mismatch.

Make the tag parameter of Element.__init__ and the parent and tag
parameters of SubElement positional-only to align with the C
accelerator.
2026-03-30 19:42:24 +03:00
Victor Stinner 7bdfce0d3a gh-145056: Accept frozendict in xml.etree (#145508)
Element and SubElement of xml.etree.ElementTree now also accept
frozendict for attrib.

Export _PyDict_CopyAsDict() function.
2026-03-05 12:55:28 +01:00
Serhiy Storchaka f3759d21dd gh-142306: Improve errors for Element.remove() (GH-142308)
* Raise TypeError for non-element argument in the Python implementation
  too.
* Include the repr of the elements in the ValueError error message.
2026-01-12 11:49:18 +02:00
Hugo van Kemenade d2abd5733b gh-76007: Deprecate VERSION in xml.etree.ElementTree & version in xml.sax.expatreader & xml.sax.handler (#142898) 2025-12-18 14:22:23 +00:00
Petr ViktorinandHugo van Kemenade 1cc7551b3f gh-142754: Ensure that Element & Attr instances have the ownerDocument attribute (#142794)
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
2025-12-16 12:20:48 +00:00
Seth Michael LarsonandJacob Walls 08d8e18ad8 gh-142145: Remove quadratic behavior in node ID cache clearing (GH-142146)
* Remove quadratic behavior in node ID cache clearing

Co-authored-by: Jacob Walls <38668450+jacobtylerwalls@users.noreply.github.com>

* Add news fragment

---------

Co-authored-by: Jacob Walls <38668450+jacobtylerwalls@users.noreply.github.com>
2025-12-02 23:16:37 -08:00
Osama AbdelkaderandSerhiy Storchaka a486d452c7 gh-140601: Add ResourceWarning to iterparse when not closed (GH-140603)
When iterparse() opens a file by filename and is not explicitly closed,
emit a ResourceWarning to alert developers of the resource leak.

Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>
Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
2025-11-13 21:05:28 +02:00
Kira e0245c789f gh-135640: Adds more type checking to ElementTree (GH-135643) 2025-07-03 10:48:47 +03:00
Bénédikt Tran 04bc681e7c gh-131938: Update exception message for Element.remove() when an element is not found (#131972)
The exception message for `xml.etree.ElementTree.Element.remove` when an element is not found
has been updated from "list.remove(x): x not in list" to "Element.remove(x): element not found".
2025-04-04 15:04:07 +00:00
Stephen Morton 6ea04da270 gh-128302: Fix bugs in xml.dom.xmlbuilder (GH-128284)
* Allow DOMParser.parse() to correctly handle DOMInputSource instances
  that only have a systemId attribute set.
* Fix DOMEntityResolver.resolveEntity(), which was broken by the
  Python 3.0 transition.
* Add Lib/test/test_xml_dom_xmlbuilder.py with few tests.
2025-01-07 12:40:41 +02:00
Xie Yanbo 253c6a0b2f Fix typos in comments and test code (#122846) 2024-08-11 21:16:41 -07:00
Victor Stinner 05df063ad8 gh-120417: Fix "imported but unused" linter warnings (#120461)
Add __all__ to the following modules:
importlib.machinery, importlib.util and xml.sax.

Add also "# noqa: F401" in collections.abc,
subprocess and xml.sax.

* Sort __all__; remove collections.abc.__all__; remove private names

* Add tests
2024-06-14 20:39:50 +02:00
Victor Stinner 6ae254aaa0 gh-120417: Add #noqa to used imports in the stdlib (#120421)
Tools such as ruff can ignore "imported but unused" warnings if a
line ends with "# noqa: F401". It avoids the temptation to remove
an import which is used effectively.
2024-06-13 16:14:50 +02:00
Jacob Walls 6b606522ca gh-119577: Adjust DeprecationWarning when testing element truth values in ElementTree (GH-119762)
Adjust DeprecationWarning when testing element truth values in ElementTree, we're planning to go with the more natural True return rather than a disruptive harder to code around exception raise, and are deferring the behavior change for a few more releases.
2024-06-06 20:18:30 -07:00
898f6de63f gh-101549: fix documentation of xml.etree.ElementInclude (#101550)
Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
Co-authored-by: Adam Turner <9087854+aa-turner@users.noreply.github.com>
2024-04-11 14:23:52 +00:00
Sebastian Pipping 6a95676bb5 gh-115398: Expose Expat >=2.6.0 reparse deferral API (CVE-2023-52425) (GH-115623)
Allow controlling Expat >=2.6.0 reparse deferral (CVE-2023-52425) by adding five new methods:

- `xml.etree.ElementTree.XMLParser.flush`
- `xml.etree.ElementTree.XMLPullParser.flush`
- `xml.parsers.expat.xmlparser.GetReparseDeferralEnabled`
- `xml.parsers.expat.xmlparser.SetReparseDeferralEnabled`
- `xml.sax.expatreader.ExpatParser.flush`

Based on the "flush" idea from https://github.com/python/cpython/pull/115138#issuecomment-1932444270 .

### Notes

- Please treat as a security fix related to CVE-2023-52425.

Includes code suggested-by: Snild Dolkow <snild@sony.com>
and by core dev Serhiy Storchaka.
2024-02-29 14:52:50 -08:00
Serhiy Storchaka ca715e56a1 gh-69893: Add the close() method for xml.etree.ElementTree.iterparse() iterator (GH-114534) 2024-02-04 17:25:21 +02:00
Sam Gross 66f95ea6a6 gh-114737: Revert change to ElementTree.iterparse "root" attribute (GH-114755)
Prior to gh-114269, the iterator returned by ElementTree.iterparse was
initialized with the root attribute as None. This restores the previous
behavior.
2024-01-31 13:22:24 +02:00
Sam Gross ce01ab536f gh-101438: Avoid reference cycle in ElementTree.iterparse. (GH-114269)
The iterator returned by ElementTree.iterparse() may hold on to a file
descriptor. The reference cycle prevented prompt clean-up of the file
descriptor if the returned iterator was not exhausted.
2024-01-23 20:14:46 +00:00
Serhiy Storchaka 154477be72 gh-50002: xml.dom.minidom now preserves whitespaces in attributes (GH-107947)
Also double quotes (") are now only quoted in attributes.
2023-08-23 15:23:41 +03:00
Jacob Walls d717be04dc gh-83122: Deprecate testing element truth values in ElementTree (#31149)
When testing element truth values, emit a DeprecationWarning in all implementations.

This had emitted a FutureWarning in the rarely used python-only implementation since ~2.7 and has always been documented as a behavior not to rely on.

Matching an element in a tree search but having it test False can be unexpected. Raising the warning enables making the choice to finally raise an exception for this ambiguous behavior in the future.
2023-01-22 17:16:48 -08:00
Nikita Sobolev 745545b5bb gh-99482: remove jython compatibility parts from stdlib and tests (#99484) 2022-12-23 14:17:24 -06:00
Nick Drozd 024ac542d7 bpo-45975: Simplify some while-loops with walrus operator (GH-29347) 2022-11-26 14:33:25 -08:00
Kevin KirscheandJelle Zijlstra 58f6953d6d gh-96175: add missing self._localName assignment in xml.dom.minidom.Attr (#96176)
X-Ref: https://github.com/python/typeshed/pull/8590#discussion_r951473977

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2022-08-23 09:16:02 -07:00
Eugene Triguba a95e60db74 gh-91447: Fix findtext to only give an empty string on None (GH-91486)
The API documentation for [findtext](https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.findtext) states that this function gives back an empty string on "no text content." With the previous implementation, this would give back a empty string even on text content values such as 0 or False. This patch attempts to resolve that by only giving back an empty string if the text attribute is set to `None`. Resolves #91447.

Automerge-Triggered-By: GH:gvanrossum
2022-08-01 09:52:39 -07:00
Victor Stinner fd76eb547d gh-94383: Remove ElementTree.Element.copy() method (#94384)
xml.etree: Remove the ElementTree.Element.copy() method of the pure
Python implementation, deprecated in Python 3.10, use the copy.copy()
function instead. The C implementation of xml.etree has no copy()
method, only a __copy__() method.
2022-07-04 15:51:01 +02:00
Serhiy Storchaka d7db9dc3cc gh-91810: Fix regression with writing an XML declaration with encoding='unicode' (GH-93426)
Suppress writing an XML declaration in open files in ElementTree.write()
with encoding='unicode' and xml_declaration=None.

If file patch is passed to ElementTree.write() with encoding='unicode',
always open a new file in UTF-8.
2022-06-14 07:25:33 +03:00