[Zope3-checkins] CVS: Zope3/src/zope/app/dublincore -
xmlmetadata.py:1.4
Fred L. Drake, Jr.
fred at zope.com
Thu Aug 28 20:27:33 EDT 2003
Update of /cvs-repository/Zope3/src/zope/app/dublincore
In directory cvs.zope.org:/tmp/cvs-serv2402
Modified Files:
xmlmetadata.py
Log Message:
refactor to move some namespace handling to be less intrusive in the
dumpString() function; it might be somewhat reusable as well
=== Zope3/src/zope/app/dublincore/xmlmetadata.py 1.3 => 1.4 ===
--- Zope3/src/zope/app/dublincore/xmlmetadata.py:1.3 Wed Aug 27 00:43:55 2003
+++ Zope3/src/zope/app/dublincore/xmlmetadata.py Thu Aug 28 19:27:32 2003
@@ -32,14 +32,45 @@
dublin_core_namespaces = dcterms.DC_NS, dcterms.DCTERMS_NS
+DEFAULT_NAMESPACE_PREFIXES = {
+ # uri: prefix,
+ dcterms.DC_NS: "dc",
+ dcterms.DCTERMS_NS: "dcterms",
+ dcterms.XSI_NS: "xsi",
+ }
+
+class NamespaceTracker:
+ def __init__(self, mapping=None):
+ self._mapping = {}
+ self._used = {}
+ if mapping:
+ self._mapping.update(mapping)
+ self._counter = 0
+
+ def encode(self, (uri, localname)):
+ if not uri:
+ return localname
+ if uri not in self._mapping:
+ self._counter += 1
+ prefix = "ns%d" % self._counter
+ self._mapping[uri] = prefix
+ self._used[prefix] = uri
+ else:
+ prefix = self._mapping[uri]
+ if prefix not in self._used:
+ self._used[prefix] = uri
+ if prefix:
+ return "%s:%s" % (prefix, localname)
+ else:
+ return localname
+
+ def getPrefixMappings(self):
+ return self._used.items()
+
+
def dumpString(mapping):
sio = StringIO()
- nsmap = {
- # prefix: [uri, used],
- dcterms.DC_NS: ("dc", False),
- dcterms.DCTERMS_NS: ("dcterms", False),
- dcterms.XSI_NS: ("xsi", False),
- }
+ nsmap = NamespaceTracker(DEFAULT_NAMESPACE_PREFIXES)
items = mapping.items()
items.sort()
prev = None
@@ -51,20 +82,12 @@
prev = group
if name in dcterms.name_to_element:
element, t = dcterms.name_to_element[name]
- nsuri, localname = element
- if nsuri not in nsmap:
- prefix = "ns%d" % (len(nsmap) - 2)
- nsmap[nsuri] = prefix, True
- else:
- prefix, used = nsmap[nsuri]
- if not used:
- nsmap[nsuri] = prefix, True
- qname = "%s:%s" % (prefix, localname)
+ qname = nsmap.encode(element)
if not type:
type = t
if type:
- type = " xsi:type=" + quoteattr(type)
- nsmap[dcterms.XSI_NS] = "xsi", True
+ type = " %s=%s" % (nsmap.encode((dcterms.XSI_NS, "type")),
+ quoteattr(type))
for value in values:
sio.write(" <%s%s>\n %s\n </%s>\n"
% (qname, type, _encode_string(value), qname))
@@ -75,9 +98,8 @@
sio = StringIO()
sio.write("<?xml version='1.0' encoding='utf-8'?>\n"
"<metadata")
- for uri, (prefix, used) in nsmap.iteritems():
- if used:
- sio.write("\n xmlns:%s=%s" % (prefix, quoteattr(uri)))
+ for prefix, uri in nsmap.getPrefixMappings():
+ sio.write("\n xmlns:%s=%s" % (prefix, quoteattr(uri)))
sio.write(">\n")
sio.write(content)
sio.write("</metadata>\n")
More information about the Zope3-Checkins
mailing list