Skip to content

Commit

Permalink
Let ElementTreeProducer use the available namespaces
Browse files Browse the repository at this point in the history
ElementTreeProducer would ignore the namespace prefixes that were available in the element tree, and always generate new prefixes like ns00, ns01 etc.
  • Loading branch information
regebro committed Jun 11, 2018
1 parent 0cf95e6 commit 6f9e371
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ Bugs fixed
and the parser participates in a reference cycle.
Original patch by Julien Greard.

* ElementTreeProducer no longer ignores the namespace prefixes that were available
in the element tree, and now only generates nsXX prefixes if undefined prefixes
are encountered.


4.2.1 (2018-03-21)
==================
Expand Down
12 changes: 11 additions & 1 deletion src/lxml/sax.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ def __init__(self, element_or_tree, content_handler):
from xml.sax.xmlreader import AttributesNSImpl as attr_class
self._attr_class = attr_class
self._empty_attributes = attr_class({}, {})
self._prefix_map = dict((v, k) for (k, v) in element.nsmap.items())

def saxify(self):
self._content_handler.startDocument()
Expand Down Expand Up @@ -238,8 +239,17 @@ def _build_qname(self, ns_uri, local_name, prefixes, new_prefixes):
try:
prefix = prefixes[ns_uri]
except KeyError:
prefix = prefixes[ns_uri] = 'ns%02d' % len(prefixes)
# New prefix
try:
prefix = self._prefix_map[ns_uri]
except KeyError:
# Unknown prefix, generate one
prefix = prefixes[ns_uri] = 'ns%02d' % len(prefixes)
new_prefixes.append( (prefix, ns_uri) )

if prefix is None:
# Default namespace
return local_name
return prefix + ':' + local_name

def saxify(element_or_tree, content_handler):
Expand Down

0 comments on commit 6f9e371

Please sign in to comment.