Lxml:tex中的和号

2024-10-16 17:21:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用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>

脚本:

^{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>

我想保留&quot;和{}。我甚至试过用

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

但他们都没能解决这个问题。在

然后我尝试用&quot;手动替换“with &quot;。在

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>

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


Tags: 文件textexampletagxmlampattr1quot
1条回答
网友
1楼 · 发布于 2024-10-16 17:21:20

{{cd2>编码的是^字符。&quot;是字符{}的xml编码。字符"和{}不需要编码,因此lxml不对它们进行编码。在

你又试过解码文件了吗?它应该像你期望的那样工作。如果需要再次对文档中的字符串进行编码(将&转换为&amp;等),请在生成新的xml文档之前对lxml树中的单个字符串进行编码。在

相关问题 更多 >