python-3.x - 用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>
解决方案
你得到换行符是因为有换行符:
<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
推荐阅读
- oracle - 如何比较 2 列并返回 oracle SQL 中的差异
- gstreamer - 如何使用 Deepstream SDK 拍摄视频并仅提取 jpg 中的帧
- spring - 多行 AggregateItemReader 未按 spring-batch-samples 中的建议工作
- machine-learning - BigQuery ML - 一次迭代后线性回归器训练停止
- c# - 如何阻止我的代码最后循环?
- powershell - 我尝试使用 powershell 安装 yarn 包。首先我输入了 npm install -g yarn 然后我输入了 yarn install。但我收到以下错误
- flutter - SizedBox() 错误“位置参数太多:预期 2 个,但找到 4 个。尝试删除额外的参数。” 扑
- javascript - 节点 Js | 无法 POST FORM 将 JavaScript 值附加到后端/错误值
- c# - 使用 Windows.Devices.WiFiDirect 与 Microsoft 显示适配器自动连接
- visual-studio - 尝试调试 Visual Studio 2019 解决方案时出现错误“IntelliTrace 代码失败 (0x80131509)”