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>