我想向xml.etree.ElementTree的某个Element实例添加一个属性,以便将卫星数据(如numpy.ndarray )存储到一些树的节点中。这是可能的吗,因为该对象不公开__dict__和__slot__
我知道我可以使用get/set方法来填充节点属性,但是如果它持有str以外的其他对象,就不能被序列化为str。
Traceback (most recent call last):
File "latexer.py", line 576, in <module>
main(sys.argv)
File "latexer.py", line 565, in main
r.dump(**k)
File "latexer.py", line 406, in dump
code = self.__fileFormats[ufformat]()
File "latexer.py", line 416, in getXML
rawstr = ET.tostring(self._document, encoding='utf-8', method='xml')
File "C:\Python33\lib\xml\etree\ElementTree.py", line 1171, in tostring
ElementTree(element).write(stream, encoding, method=method)
File "C:\Python33\lib\xml\etree\ElementTree.py", line 828, in write
serialize(write, self._root, qnames, namespaces)
File "C:\Python33\lib\xml\etree\ElementTree.py", line 990, in _serialize_xml
_serialize_xml(write, e, qnames, None)
File "C:\Python33\lib\xml\etree\ElementTree.py", line 990, in _serialize_xml
_serialize_xml(write, e, qnames, None)
File "C:\Python33\lib\xml\etree\ElementTree.py", line 990, in _serialize_xml
_serialize_xml(write, e, qnames, None)
File "C:\Python33\lib\xml\etree\ElementTree.py", line 983, in _serialize_xml
v = _escape_attrib(v)
File "C:\Python33\lib\xml\etree\ElementTree.py", line 1139, in _escape_attrib
_raise_serialization_error(text)
File "C:\Python33\lib\xml\etree\ElementTree.py", line 1105, in _raise_serialization_error
"cannot serialize %r (type %s)" % (text, type(text).__name__)
TypeError: cannot serialize 1 (type int)有没有办法添加bool或integer之类的属性,然后将其序列化为XML?
发布于 2015-11-08 23:47:27
在阅读了其他一些关于这个问题的文章后,我接受了这个问题没有直接的,优雅的解决方案,因为-有很好的理由- nat所有的对象都可以隐式地转换为string。
然后,我找到了一种中间方法。该技术包括酸洗十六进制化的对象。当我想要访问它时,只需调用相反的过程。
我知道它在数据存储和计算开销方面效率不高,但它可以工作并解决了我的问题,因为我的树需要转储到XML中,然后重新打开。
代码如下所示:
def _fillNode(self, node, text=None, **kwargs):
"""Fill a given node with text and arguments (serialized if non string) from kwargs"""
node.text = text
for (k, v) in kwargs.items():
# Append string as this:
if isinstance(v, str):
node.set(k, v)
# If not a string pickle, hexlify and encode:
else:
node.set(k, binascii.hexlify(pickle.dumps(v)).decode())
return node
def _getAttribute(self, node, key, default=None):
"""Get node attribute as string but try first to deserialize it"""
# Try to recover string formated data:
value = node.get(key)
if value:
try:
# try to decode, unhexlify and unpickle:
return pickle.loads(binascii.unhexlify(value.encode()))
except:
# If not return as this
return value
else:
return defaulthttps://stackoverflow.com/questions/33588069
复制相似问题