gpt4 book ai didi

python - Lxml : Ampersand in text

转载 作者:太空宇宙 更新时间:2023-11-03 17:45:08 24 4
gpt4 key购买 nike

我在使用 lxml 时遇到问题

我正在使用 lxml 解析 xml 文件,然后再次将其写回新的 xml 文件。

输入文件:

<tag1>
<tag2 attr1="a1">&quot; example text &quot;</tag2>
<tag3>
<tag4 attr2="a2">&quot; example text &quot;</tag4>
<tag5>
<tag6 attr3="a3">&apos; example text &apos;</tag6>
</tag5>
</tag3>
</tag1>

脚本:

    from lxml import etree
parser = etree.XMLParser(remove_comments=False,strip_cdata=False,resolve_entities=False)
tree = etree.parse("input.xml")
tree.write("out.xml")

输出:

<tag1>
<tag2 attr1="a1"> " example text " </tag2>
<tag3>
<tag4 attr2="a2"> " example text " </tag4>
<tag5>
<tag6 attr3="a3"> ' example text ' </tag6>
</tag5>
</tag3>
</tag1>

我想保留 "' 。我什至尝试使用

f = open('output.xml', 'w')
f.write(etree.tostring(tree1.getroot(),encoding="UTF-8",xml_declaration=False))
f.close()

但是他们都没有解决这个问题。

然后我尝试手动将 "替换为 "

root = tree.getroot()
tag_elements = root.iter()
for tag in tag_elements:
tag_text = tag.text
if tag_text is not None:
tag_text1 = tag_text.replace("\"","&quot;")
tag.text = tag_text1

但这给出了以下输出

<tag1>
<tag2 attr1="a1"> &amp;quot; example text &amp;quot; </tag2>
<tag3>
<tag4 attr2="a2"> &amp;quot; example text &amp;quot; </tag4>
<tag5>
<tag6 attr3="a3"> &apos; example text &apos; </tag6>
</tag5>
</tag3>
</tag1>

它将 & 替换为 & 。我在这里很困惑。请帮我解决这个问题。

最佳答案

& 是字符& 的xml 编码。 "是字符"的xml编码,字符"'不需要编码,因此 lxml 不会对它们进行编码。

您是否尝试再次解码该文档?它应该像您期望的那样工作。如果您需要再次对文档中的字符串进行编码(将 & 转换为 & 等),请在生成新的 xml 之前对 lxml 树中的各个字符串进行编码文档。

关于python - Lxml : Ampersand in text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29922680/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com