2017-05-12 36 views
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") 

這種錯誤了 enter image description here

,這是我期待的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> 

回答

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>