[英]lxml create CDATA element
我正在嘗試根據https://lxml.de/apidoc/lxml.etree.html#lxml.etree.CDATA創建 CDATA 元素
我的代碼的簡化版本如下所示:
description = ET.SubElement(item, "description")
description.text = CDATA('test')
但是當我后來嘗試將其轉換為字符串時:
xml_str = ET.tostring(self.__root, xml_declaration=True).decode()
我得到一個例外
cannot serialize <lxml.etree.CDATA object at 0x122c30ef0> (type CDATA)
你能告訴我我錯過了什么嗎?
這是一個簡單的例子:
import xml.etree.cElementTree as ET
from lxml.etree import CDATA
root = ET.Element('rss')
root.set("version", "2.0")
description = ET.SubElement(root, "description")
description.text = CDATA('test')
xml_str = ET.tostring(root, xml_declaration=True).decode()
print(xml_str)
lxml.etree
和xml.etree
是兩個不同的庫; 您應該選擇一個並堅持使用它,而不是同時使用兩者並嘗試將一個創建的對象傳遞給另一個。
一個工作示例,僅使用 lxml:
import lxml.etree as ET
from lxml.etree import CDATA
root = ET.Element('rss')
root.set("version", "2.0")
description = ET.SubElement(root, "description")
description.text = CDATA('test')
xml_str = ET.tostring(root, xml_declaration=True).decode()
print(xml_str)
您可以在https://replit.com/@CharlesDuffy2/JovialMediumLeadership 自行運行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.