Skip to content

Сonvenient escaping for XML attribute values #140531

@Dml3Y

Description

@Dml3Y

Feature or enhancement

Proposal:

Proposed Feature: Add escape_attr function to xml.sax.saxutils

Problem

Currently, developers need to choose between:

  • escape() - doesn't handle quotes (for text content)
  • quoteattr() - adds quoting and escaping (for attributes)

Sometimes we need just escaping for attributes without the automatic quoting.

Solution

Add escape_attr() function that escapes all XML special characters including quotes, but doesn't add the outer quotes.

Benefits

  • Cleaner API for attribute value escaping
  • Maintains backward compatibility
  • Consistent with existing saxutils design
def escape_attr(data):
    """Escape string for use in XML attributes, including quotes.
    
    This is a convenience function that escapes all special characters
    required for XML attributes, including both single and double quotes.
    """
    return escape(data, entities={'"': """, "'": "'"})

Note in escape function:

"""
    Note: This function is intended for escaping text content, not attributes.
    For attributes, use quoteattr() or escape_attr().
"""

Has this already been discussed elsewhere?

No response given

Links to previous discussion of this feature:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    pendingThe issue will be closed if no feedback is providedstdlibStandard Library Python modules in the Lib/ directorytopic-XMLtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions