[英]trying to add element to xmeml format XML with xml.etree.ElementTree
[英]Add attribute to an Element of xml.etree.ElementTree and make serializable to XML
我想从xml.etree.ElementTree
中向Element
某些实例添加属性,以便将诸如numpy.ndarray
卫星数据存储到某些树的节点中。 因为对象不公开__dict__
和__slot__
是有可能的吗?
我知道我可以使用get
/ set
方法填充node属性,但是如果它包含str
以外的其他对象,则不能将其序列化为XML。
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?
在阅读了有关此问题的其他文章之后,我接受了对该问题没有直接,优雅的解决方案,因为–出于充分的理由–可以将所有对象都隐式转换为字符串。
然后,我找到了一种中间方法。 该技术包括腌制六角形的物体。 当我要访问它时,只需调用相反的过程即可。
我知道这在数据存储和计算开销方面不是很有效,但是它可以解决我的问题,因为我的树需要转储为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 default
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.