向元素添加属性xml.etree.ElementTree并使其可序列化为XML

2024-09-30 03:23:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为xml.etree.ElementTree中的Element的某个实例添加一个属性,以便将numpy.ndarray等卫星数据存储到某些树的节点中。因为对象不公开__dict__和{},所以这可能吗?在

我知道我可以使用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或{},然后将其序列化为XML?在


Tags: inpyself属性liblinexmlserialize
1条回答
网友
1楼 · 发布于 2024-09-30 03:23:42

在阅读了其他一些关于这个问题的文章之后,我承认这个问题并没有直接、优雅的解决方案,因为——有充分的理由——nat所有的对象都可以隐式地转换成字符串。在

然后,我找到了一个中间的方法。这项技术包括腌制六边形物体。当我想访问它时,只需调用反向过程。在

我知道它在数据存储和计算开销方面效率不高,但它有效并解决了我的问题,因为我的树需要转储到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

相关问题 更多 >

    热门问题