如何使用 ElementTree python 在 xml 解析器中处理 CDATA?

Posted

技术标签:

【中文标题】如何使用 ElementTree python 在 xml 解析器中处理 CDATA?【英文标题】:How to handle CDATA in xml parser using ElementTree python? 【发布时间】:2017-02-15 23:06:57 【问题描述】:

我刚刚启动 python 并尝试使用 ElementTree 解析 xml 文件。但问题是我有一个带有 CDATA 的标签,该标签在 tree.write.

之后被删除

所以基本上我有这个标签

<content><![CDATA[eclipse.ver=1&encoding/ <project>=UTF-8$line.sep]]></content>

改成

<content>eclipse.ver=1&encoding/&lt;project&gt;=UTF-8$line.sep</content>

我试过用谷歌搜索,但不是很有帮助。那么任何人都可以帮助我,我怎样才能在标签中获得完全相同的内容??

【问题讨论】:

***.com/questions/174890/…的可能重复 我认为这个问题是输出 xml 文件硬编码 xml 标签。但我想编辑包含 CDATA 的 xml 文件。 【参考方案1】:
from xml.etree.ElementTree import ElementTree
import re
l=[]
tree = ElementTree()
tree.parse("YOURFILE.xml")
root = tree.getroot()

for parent in root.findall('.//content/..'):
    for child in parent.findall("content"):
        if(child.text != None):
            l.append(child.text)        

【讨论】:

这不能回答问题。

以上是关于如何使用 ElementTree python 在 xml 解析器中处理 CDATA?的主要内容,如果未能解决你的问题,请参考以下文章