Tom Kralidis schrieb am 12.05.2015 um 20:03:
Hi: using lxml 3.3.5, we have XML documents with elements having QName type values. We would like to implement etree.cleanup_namespaces but are finding that this affects downstream parsers/validators complaining about undeclared namespace prefixes. Below is an isolated example:
from lxml import etree
nsmap = { 'ogc': 'http://www.opengis.net/ogc', 'ows': 'http://www.opengis.net/ows', 'gml': 'http://www.opengis.net/gml' }
root = etree.Element('{http://www.opengis.net/ogc}Filter', nsmap=nsmap)
typename = etree.SubElement(root, '{http://www.opengis.net/ogc}typeName') typename.text = etree.QName('http://www.opengis.net/gml', 'Envelope')
typename2 = etree.SubElement(root, '{http://www.opengis.net/ogc}typeName') typename2.text = etree.QName('{http://www.opengis.net/gml}Envelope')
print etree.tostring(root, pretty_print=True) etree.cleanup_namespaces(root) print etree.tostring(root, pretty_print=True)
Here we would like the gml namespace declaration, but it looks like cleanup_namespaces is throwing out namespace declarations even if they apply to element content.
Are there any workarounds we can use/implement to cleanup unused namespaces while preserving those for element content per above?
I'm getting this as output: <ogc:Filter xmlns:ogc="http://www.opengis.net/ogc"> <ogc:typeName>gml:Envelope</ogc:typeName> <ogc:typeName>gml:Envelope</ogc:typeName> </ogc:Filter> So your problem is that "gml:Envelope" is actually text content and not structure, which means that lxml ignores it when removing unused namespace declarations (and the "gml" prefix is really unused, except that some downstream processor wants it to be there). QName() is only special at the time of assignment. Afterwards, it's turned into regular text content. So there is no way lxml could figure out later that it's something it needs to care about. So, the work-around I would suggest is to not call cleanup_namespaces() and to keep the namespace declarations as they are in the tree. If repetition is a problem, use compression. Or is there an actual reason why additional namespace declarations hurt here? Stefan