首页 > 解决方案 > 用lxml读取CDATA,行尾问题

问题描述

您好,我正在解析一个包含一堆 CDATA 部分的 xml 文档。到目前为止,我的工作没有任何问题。我意识到,当我阅读 an 元素并获取文本 aribute 时,我会在开头和文本结尾处获得行尾字符。

一段重要的代码如下:

for comments in self.xml.iter("Comments"):
    for comment in comments.iter("Comment"):
        description = comment.get('Description')

        if language == "Arab":
            tag = self.name + description
            text = comment.text

问题出在元素评论处,他的做法如下:

<Comment>
<![CDATA[Usually made it with not reason]]>

我尝试获取文本属性,但我得到了这样的结果:

\nUsually made it with not reason\n

我知道我可以做一个脱衣舞之类的。但我想从根本上解决问题,也许之前有一些选项可以用 elementree 解析。

当我解析 xml 文件时,我正在这样做:

tree = ET.parse(xml)

最小的可重现示例

import xml.etree.ElementTree as ET

filename = test.xml  #Place here your path test xml file

tree = ET.parse(filename)
root = tree.getroot()
Description = root[0]
text = Description.text

print (text)

最小的xml文件

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Description>
<![CDATA[Hello world]]>
</Description>

标签: python-3.xxml-parsingelementtree

解决方案


你得到换行符是因为有换行符

<Comment>
<![CDATA[Usually made it with not reason]]>
</Comment>

否则为什么要<![CDATA开始</Comment新的路线?

如果您不想要换行符,请删除它们:

<Comment><![CDATA[Usually made it with not reason]]></Comment>

元素内的所有内容都计入其字符串值。

<![CDATA[...]]>不是一个元素,它是一个解析器标志。它改变了 XML 解析器读取封闭字符的方式。您可以在同一个元素中有多个 CDATA 部分,随意在“常规模式”和“cdata 模式”之间切换:

<Comment>normal text <![CDATA[
    CDATA mode, this may contain <unescaped> Characters!
]]> now normal text again
<![CDATA[more special text]]> now normal text again
</Comment>

CDATA 部分之前和之后的任何换行符都计入“普通文本”部分。当解析器读取此内容时,它将创建一个由各个部分组成的长字符串:

normal text 
    CDATA mode, this may contain <unescaped> Characters!
 now normal text again
more special text now normal text again

推荐阅读