Re: [lxml] Support default_namespace parameter in write method?

Charlie Clark schrieb am 07.12.2014 um 12:00:
Am .12.2014, 10:05 Uhr, schrieb Stefan Behnel:
Not sure. It's due to an inherent difference in the tree models of libxml2 and ElementTree: the latter does not know about prefixes at all and handles them only in the serialiser, whereas libxml2 takes them from the in-memory tree. There is no override in libxml2's serialiser, so it would require modifying the tree's namespaces during serialisation (i.e. modification during a supposed read-only operation). I guess it's worth trying out, though.
I thought there might be something like that. But would it be possible to allow the registration of an empty namespace (as ElementTree allows)? Currently this is only possible with nsmap. BTW. what are the constraints on nsmap? The attribute is not writable but __setitem__ does not raise an exception.
Yes, it's actually documented (see docstring) that changing an Element's nsmap has no effect. The property returns a real dict that contains all prefix-namespace mappings known in the context of this Element in the tree. But it has no actual connection to that Element that could pass back modifications. I think the problem is that it was never obvious to me what the semantics should be here. It feels wrong if modifying a mapping that includes all ancestor namespaces changes the namespaces defined on a specific node. And would it then update the subtree of that Element? Then reading the property would give you access to the ancestor state and modifying it would change the children? Strange. If you change the namespace of a prefix, would it then have to go back to the ancestor that defined the modified prefix and changing its entire subtree? That sounds even worse. And what would happen if you deleted a prefix that's in use? I agree that the feature of modifying the namespace mapping is missing, though. If someone has a good idea how this should work, I'm all eyes.
register_namespace("", "http://example.com/whatever") # works in ElementTree but not in lxml
Ah, yes. Not sure the error you get was intended. It would be easy to make this work, but then, register_namespace() changes global library state. Globally setting up a prefix-namespace mapping is not a great idea already (it's ok as long as the prefix is a generally accepted de-facto standard), but setting a global default namespace seems like asking for trouble and interference with other code. The mapping is bidirectional and if multiple default namespace mappings are registered, one will overwrite the other and the result will depend on who happens to be last. Rearrange some imports and loose your pretty output? If you're lucky, you'll at least see some of your tests fail, but I guess prefixes are rarely tested for. Stefan
participants (1)
-
Stefan Behnel