我在使用lxml时遇到问题
我使用lxml解析一个xml文件,并再次将其写回一个新的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>
脚本:
^{pr2}$输出:
<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()
但他们都没能解决这个问题。在
然后我尝试用"
手动替换“with "
。在
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("\"",""")
tag.text = tag_text1
但这给出了下面的输出
<tag1>
<tag2 attr1="a1"> &quot; example text &quot; </tag2>
<tag3>
<tag4 attr2="a2"> &quot; example text &quot; </tag4>
<tag5>
<tag6 attr3="a3"> ' example text ' </tag6>
</tag5>
</tag3>
</tag1>
它将amp;替换为&
。我很困惑。请帮我解决这个问题。在
{{cd2>编码的是^字符。}的xml编码。字符}不需要编码,因此lxml不对它们进行编码。在
"
是字符{"
和{你又试过解码文件了吗?它应该像你期望的那样工作。如果需要再次对文档中的字符串进行编码(将
&
转换为&
等),请在生成新的xml文档之前对lxml树中的单个字符串进行编码。在相关问题 更多 >
编程相关推荐