使用元素树提取元素文字文本

汤姆·托马斯

我有以下带有<Description>标记的XML ,其中包含以下包含特殊字符的文本。

<branch>
   <Description>
      Here are few steps to make these settings
      1)    Tools &lt;&lt; Internet options 2)  Click on General tab
   </Description>
</branch>

现在,当我尝试检索描述文本时,得到以下结果,该结果自动转换&lt;为 >。所以代码和结果如下。

代码 -

from xml.etree import ElementTree as ET 
tree = ET.parse(inputFile) # copy the above xml into any file and pass the path to inputFile 

    root = tree.getroot()

    for description in root.iter('Description'):
        print(description.text) 

我需要描述文本标签中的字符串文字。我们如何得到它?

预期的 -

Here are few steps to make these settings
          1)    Tools >> Internet options 2)    Click on General tab
科迪

您可以简单地使用html.escape()重新转义内容:

import html
from xml.etree import ElementTree as ET

tree = ET.parse('test.xml')
root = tree.getroot()

for description in root.iter('Description'):
    print(html.escape(description.text))

结果:

Here are few steps to make these settings
1)    Tools &lt;&lt; Internet options 2)  Click on General tab

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章