Skip to content

ElementTree.tostring(..., default_namespace=...) incorrectly strips namespace from attributes #113581

Description

@hexagonrecursion

Bug report

Bug description:

import xml.etree.ElementTree as ET
foo = ET.Element('{http://example.com}foo', {'{http://example.com}baz': '1234'})
# Expected output: <foo xmlns="http://example.com" xmlns:ns0="http://example.com" ns0:baz="1234" />
# Prints: <foo xmlns="http://example.com" baz="1234" />
print(ET.tostring(foo, default_namespace='http://example.com', encoding="unicode"))

A careful reading of the "Namespaces in XML" specification suggests that the two xml documents are not the same.

https://www.w3.org/TR/xml-names/#defaulting
The namespace name for an unprefixed attribute name always has no value.

In the expected output the namespace name of the attribute is http://example.com, but in the actual output the namespace name of the attribute has no value.

Note that our parser does correctly implement this part of the "Namespaces in XML" specification

# Prints {'{http://example.com}baz': '1234'}
print(ET.XML('''<foo xmlns="http://example.com" xmlns:ns0="http://example.com" ns0:baz="1234" />''').attrib)
# Prints {'baz': '1234'}
print(ET.XML('''<foo xmlns="http://example.com" baz="1234" />''').attrib)

Related:

Note 61290 is about tostring() raising an exception when it should not. My bug on the other hand is about tostring() producing incorrect output.

CPython versions tested on:

3.12

Operating systems tested on:

Linux

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytopic-XMLtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions