简体   繁体   English

lxml 创建 CDATA 元素

[英]lxml create CDATA element

I am trying to create CDATA element as per https://lxml.de/apidoc/lxml.etree.html#lxml.etree.CDATA我正在尝试根据https://lxml.de/apidoc/lxml.etree.html#lxml.etree.CDATA创建 CDATA 元素

The simplified version of my code looks like this:我的代码的简化版本如下所示:

description = ET.SubElement(item, "description")
description.text = CDATA('test')

But when I later try to convert it to string:但是当我后来尝试将其转换为字符串时:

xml_str = ET.tostring(self.__root, xml_declaration=True).decode()

I get an exception我得到一个例外

cannot serialize <lxml.etree.CDATA object at 0x122c30ef0> (type CDATA)

Could you advise me what am I missing?你能告诉我我错过了什么吗?

Here is a simple example:这是一个简单的例子:

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 and xml.etree are two different libraries; lxml.etreexml.etree是两个不同的库; you should pick one and stick with it, rather than using both and trying to pass objects created by one to the other.您应该选择一个并坚持使用它,而不是同时使用两者并尝试将一个创建的对象传递给另一个。

A working example, using lxml only:一个工作示例,仅使用 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)

You can run this yourself at https://replit.com/@CharlesDuffy2/JovialMediumLeadership您可以在https://replit.com/@CharlesDuffy2/JovialMediumLeadership 自行运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM