使用Python,尝试使用十六进制的HTML逃脱字符保存XML文件



我正在使用ElementTree。我有一个解析的XML文档,看起来像这样:

<data>
    <name>
        <slash>/</slash>
    </name>
</data>

我希望能够使用HTML逃脱字符的十六进制代码保存它。

由于"/"的十六进制代码为2F,我想将XML坚持为:

<data>
    <name>
        <slash>&#x2f;</slash>
    </name>
</data>

做到这一点的Pythonic方法是什么?理想情况下,我希望这样做:

import xml.etree.ElementTree as ET
xml_doc = ET.tostring(source,method="xml")
xml_doc=change_to_html_hex_code(xml_doc)
out_file = open("output.xml",'w')
out_file.write(xml_doc)

使用lxml:

x = """<data>
    <name>
        <slash>/</slash>
    </name>
</data>"""
import lxml.etree as et
xml_doc = et.fromstring(x)
for node in xml_doc.xpath("//*[contains(text(), '/')]"):
    node.text = node.text.replace("/","&#x2f;")

print(et.tostring(xml_doc))

会给你的:

<data>
    <name>
        <slash>&amp;#x2f;</slash>
    </name>
</data>

或XML:

from xml.etree import ElementTree  as et
xml_doc = et.fromstring(x)
for node in xml_doc.iter("*"):
    if "/" in node.text:
        node.text = node.text.replace("/","&#x2f;")

要写入文件,此答案都涵盖了两个。

您可以使用编解码器模块(包含在Python中)

import codecs
def returnHex(input):
    hexitup = codecs.getencoder('hex')
    return ("&#" + hexitup(input)[0]+";")
print(returnHex('/'))

这应该返回&amp;#2f;

最新更新