-
-
Notifications
You must be signed in to change notification settings - Fork 35.3k
gh-57092: Add the validate option to xml.sax.saxutils.XMLGenerator #156800
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
serhiy-storchaka
wants to merge
3
commits into
python:main
Choose a base branch
from
serhiy-storchaka:gh-57092-xmlgen-validate
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
fe4de69
gh-156797: Escape the namespace URI in xml.sax.saxutils.XMLGenerator
serhiy-storchaka be69186
gh-57092: Add the validate option to xml.sax.saxutils.XMLGenerator
serhiy-storchaka a3a266c
Merge remote-tracking branch 'upstream/main' into gh-57092-xmlgen-val…
serhiy-storchaka File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,6 +8,8 @@ | |
| import codecs | ||
| from . import handler | ||
| from . import xmlreader | ||
| from .. import is_valid_name as _is_valid_name | ||
| from .. import is_valid_text as _is_valid_text | ||
|
|
||
| def __dict_replace(s, d): | ||
| """Replace substrings of a string using a dictionary.""" | ||
|
|
@@ -109,10 +111,16 @@ def __getattr__(self, name): | |
| newline='\n', | ||
| write_through=True) | ||
|
|
||
| def _check_name(name, what): | ||
| if not _is_valid_name(name): | ||
| raise ValueError(f'invalid {what} {name!r}') | ||
|
|
||
|
|
||
| class XMLGenerator(handler.ContentHandler): | ||
| """Content handler which writes the events back as an XML document.""" | ||
|
|
||
| def __init__(self, out=None, encoding="iso-8859-1", short_empty_elements=False): | ||
| def __init__(self, out=None, encoding="iso-8859-1", short_empty_elements=False, | ||
| *, validate=False): | ||
| handler.ContentHandler.__init__(self) | ||
| out = _gettextwriter(out, encoding) | ||
| self._write = out.write | ||
|
|
@@ -122,6 +130,7 @@ def __init__(self, out=None, encoding="iso-8859-1", short_empty_elements=False): | |
| self._undeclared_ns_maps = [] | ||
| self._encoding = encoding | ||
| self._short_empty_elements = short_empty_elements | ||
| self._validate = validate | ||
| self._pending_start_element = False | ||
|
|
||
| def _qname(self, name): | ||
|
|
@@ -156,6 +165,11 @@ def endDocument(self): | |
| self._flush() | ||
|
|
||
| def startPrefixMapping(self, prefix, uri): | ||
| if self._validate: | ||
| if prefix: | ||
| _check_name(prefix, 'namespace prefix') | ||
| if not _is_valid_text(uri): | ||
| raise ValueError(f'invalid namespace name {uri!r}') | ||
| self._ns_contexts.append(self._current_context.copy()) | ||
| self._current_context[uri] = prefix | ||
| self._undeclared_ns_maps.append((prefix, uri)) | ||
|
|
@@ -165,9 +179,15 @@ def endPrefixMapping(self, prefix): | |
| del self._ns_contexts[-1] | ||
|
|
||
| def startElement(self, name, attrs): | ||
| if self._validate: | ||
| _check_name(name, 'element name') | ||
| self._finish_pending_start_element() | ||
| self._write('<' + name) | ||
| for (name, value) in attrs.items(): | ||
| if self._validate: | ||
| _check_name(name, 'attribute name') | ||
| if not _is_valid_text(value): | ||
| raise ValueError('invalid attribute value') | ||
| self._write(' %s=%s' % (name, quoteattr(value))) | ||
| if self._short_empty_elements: | ||
| self._pending_start_element = True | ||
|
|
@@ -179,11 +199,16 @@ def endElement(self, name): | |
| self._write('/>') | ||
| self._pending_start_element = False | ||
| else: | ||
| if self._validate: | ||
| _check_name(name, 'element name') | ||
| self._write('</%s>' % name) | ||
|
|
||
| def startElementNS(self, name, qname, attrs): | ||
| name = self._qname(name) | ||
| if self._validate: | ||
| _check_name(name, 'element name') | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same remark: can you check attributes here? |
||
| self._finish_pending_start_element() | ||
| self._write('<' + self._qname(name)) | ||
| self._write('<' + name) | ||
|
|
||
| for prefix, uri in self._undeclared_ns_maps: | ||
| if prefix: | ||
|
|
@@ -193,7 +218,12 @@ def startElementNS(self, name, qname, attrs): | |
| self._undeclared_ns_maps = [] | ||
|
|
||
| for (name, value) in attrs.items(): | ||
| self._write(' %s=%s' % (self._qname(name), quoteattr(value))) | ||
| name = self._qname(name) | ||
| if self._validate: | ||
| _check_name(name, 'attribute name') | ||
| if not _is_valid_text(value): | ||
| raise ValueError('invalid attribute value') | ||
| self._write(' %s=%s' % (name, quoteattr(value))) | ||
| if self._short_empty_elements: | ||
| self._pending_start_element = True | ||
| else: | ||
|
|
@@ -204,23 +234,35 @@ def endElementNS(self, name, qname): | |
| self._write('/>') | ||
| self._pending_start_element = False | ||
| else: | ||
| self._write('</%s>' % self._qname(name)) | ||
| name = self._qname(name) | ||
| if self._validate: | ||
| _check_name(name, 'element name') | ||
| self._write('</%s>' % name) | ||
|
|
||
| def characters(self, content): | ||
| if content: | ||
| self._finish_pending_start_element() | ||
| if not isinstance(content, str): | ||
| content = str(content, self._encoding) | ||
| if self._validate and not _is_valid_text(content): | ||
| raise ValueError('invalid characters') | ||
| self._write(escape(content)) | ||
|
|
||
| def ignorableWhitespace(self, content): | ||
| if content: | ||
| self._finish_pending_start_element() | ||
| if not isinstance(content, str): | ||
| content = str(content, self._encoding) | ||
| if self._validate and content.strip(' \t\r\n'): | ||
| raise ValueError(f'invalid whitespace {content!r}') | ||
| self._write(content) | ||
|
|
||
| def processingInstruction(self, target, data): | ||
| if self._validate: | ||
| if (not _is_valid_name(target) or target.lower() == 'xml' | ||
| or '?>' in data or not _is_valid_text(data)): | ||
| raise ValueError('invalid processing instruction ' | ||
| f'{f"{target} {data}"!r}') | ||
| self._finish_pending_start_element() | ||
| self._write('<?%s %s?>' % (target, data)) | ||
|
|
||
|
|
||
3 changes: 3 additions & 0 deletions
3
Misc/NEWS.d/next/Library/2026-09-01-15-42-10.gh-issue-57092.Kx3vQb.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| Add the *validate* option to :class:`xml.sax.saxutils.XMLGenerator`. If it is | ||
| true, invalid names, illegal characters and other content which cannot be | ||
| represented in a well-formed XML document are rejected with :exc:`ValueError`. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would it be possible to validate attributes here? With the current code, you start writing before raising an error on invalid attribute. So on error, incomplete XML is written.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I do not see how can this help? We already wrote something.