【问题标题】:text and xml converting problems文本和xml转换问题
【发布时间】:2017-06-06 02:53:55
【问题描述】:

我对文本和 xml 有一些问题。我正在使用 Python 3.6.0 :: Anaconda 4.3.1 (x86_64)。 我有字符串 x 并将其转换为 xml 格式。

但是输入和输出是不同的。我假设 python 转换 & lt;进入我不想要的

结果如下所示:

import xml.etree.cElementTree as ET
x = '<SCRIPT>g(x) &lt;0</SCRIPT>' 
root = ET.fromstring(x)
print('result : ',root.text[5])

结果是

result :  <

这表明

已经变了。我希望它是

&

谢谢!!!!

【问题讨论】:

  • 请使用标记发布您的代码,而不是作为链接,并乐于提供帮助!

标签: python xml python-3.x parsing text


【解决方案1】:

如果 XML 的值为 &lt;SCRIPT&gt;g(x) &lt;0&lt;/SCRIPT&gt;,则会导致解析错误。为了避免此类错误,&amp;lt; 符号被替换为实体引用&amp;lt;

类似的实体引用包括:

&lt;    <   less than
&gt;    >   greater than
&amp;   &   ampersand 
&apos;  '   apostrophe
&quot;  "   quotation mark

要在XML解析后取回实体引用,我们可以使用字符串替换。

print('result : ',root.text.replace('&lt;','&amp;lt;')[5])

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2013-10-03
    • 2014-11-26
    • 1970-01-01
    • 2019-11-24
    • 2016-09-20
    • 2012-06-14
    • 2014-08-11
    • 2014-11-24
    • 2014-03-27
    相关资源
    最近更新 更多