1
当我解析在pythonPython的ElementTree的序列化错误写入磁盘
tree = ET.parse('existing.xml')
添加一个文件在内存中的一些XML元素到XML结构
NodeList = tree.findall(".//NodeList")
NodeList_WeWant = buildingNodeList[0]
for member in aList:
ET.SubElement(NodeList_WeWant,member)
写回磁盘
tree.write("output.sbp", encoding="utf-16")
但我得到
Traceback (most recent call last):
File "runonreal.py", line 156, in <module>
tree.write("output.sbp", encoding="utf-16")
File "C:\Python340\lib\xml\etree\ElementTree.py", line 775, in write
qnames, namespaces = _namespaces(self._root, default_namespace)
File "C:\Python340\lib\xml\etree\ElementTree.py", line 887, in _namespaces
_raise_serialization_error(tag)
File "C:\Python340\lib\xml\etree\ElementTree.py", line 1059, in _raise_serialization_error
"cannot serialize %r (type %s)" % (text, type(text).__name__)
TypeError: cannot serialize <Element 'BuildingNodeBase' at 0x099421B0> (type Element)
编辑。错误的简单复制。见下面
我的基本XML
<?xml version="1.0" encoding="UTF-8"?>
<family>
<person>
<id>100</id>
<name>Shorn</name>
<height>5.8</height>
</person>
<person>
<id>101</id>
</person>
</family>
的Python脚本
import xml.etree.ElementTree as ET
from copy import deepcopy
tree = ET.parse('basic.xml')
root = tree.getroot()
cloneFrom = tree.findall(".//person[name='Shorn']")
cloneTo = tree.findall(".//person[id='101']")
cloneTo = deepcopy(cloneFrom)
ET.SubElement(root,cloneTo)
tree.write("output.xml", encoding="utf-16")
,这是我期待的Output.xml。应将个人节点克隆到另一个人节点并写回磁盘。
<?xml version="1.0" encoding="UTF-16"?>
<family>
<person>
<id>100</id>
<name>Shorn</name>
<height>5.8</height>
</person>
<person>
<id>100</id>
<name>Shorn</name>
<height>5.8</height>
</person>
</family>