写入磁盘时,Python ElementTree Serialize Error

时间:2017-05-12 04:05:39

标签: xml python-3.x elementtree

我在python中解析文件

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")

这个错误了 enter image description here

这是我期望的output.xml。应将Person节点克隆到另一个人节点并写回磁盘。

<?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>

1 个答案:

答案 0 :(得分:0)

这里有一些问题:

  • findall()返回一个列表,而不是单个元素。
  • SubElement期望一个字符串,而不是Element对象,作为第二个参数。
  • 不删除id ='101'的元素。

这是适用于我的代码(使用Python 3.6.1测试):

import xml.etree.ElementTree as ET
from copy import deepcopy

tree = ET.parse('basic.xml')
root = tree.getroot()

remove = tree.find(".//person[id='101']")
cloneFrom = tree.find(".//person[name='Shorn']")

root.remove(remove)
root.append(deepcopy(cloneFrom))

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>