Python往事:ElementTree的单引号之谜

2023-12-17 17:36

本文主要是介绍Python往事:ElementTree的单引号之谜,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

最近在针对某款设备的界面xml进行更新过程中,被告知回稿的字串放在了一个excel文件中,而我要上传到服务器的界面用语是用xml文件封装的。再经过详细求证了翻译组提供excel文件的原因后,我决定用python来完成界面用语xml的更新,但是在使用ElementTree库的时候,却发现这个库有点小瑕疵。就是会将xml文件的表头<xml/>这段中的双引号换成了单引号,虽然单双引号在解析xml上没有影响。但是如果上提交代码时有强校验的门禁处理等规则的话,就需要额外解释了。为此针对这个问题,查看了下源码并分享一种修改方案。

我遇到的情况如下图所示,原本要替换message的信息,结果执行完替换脚本后,发现xml声明表头也被替换了。这个变更在比较软件中会显得很明显。

发生这种事情的原因在于EelementTree#write()中将表头的格式默认写成了单引号。如下源码展示了write()的实现,可以发现在_get_wirte()的with循环体中直白的执行了一句写入操作:

<?xml version='1.0' encoding='%s'?>
    def write(self, file_or_filename,encoding=None,xml_declaration=None,default_namespace=None,method=None, *,short_empty_elements=True):"""Write element tree to a file as XML.Arguments:*file_or_filename* -- file name or a file object opened for writing*encoding* -- the output encoding (default: US-ASCII)*xml_declaration* -- bool indicating if an XML declaration should beadded to the output. If None, an XML declarationis added if encoding IS NOT either of:US-ASCII, UTF-8, or Unicode*default_namespace* -- sets the default XML namespace (for "xmlns")*method* -- either "xml" (default), "html, "text", or "c14n"*short_empty_elements* -- controls the formatting of elementsthat contain no content. If True (default)they are emitted as a single self-closedtag, otherwise they are emitted as a pairof start/end tags"""if not method:method = "xml"elif method not in _serialize:raise ValueError("unknown method %r" % method)if not encoding:if method == "c14n":encoding = "utf-8"else:encoding = "us-ascii"enc_lower = encoding.lower()with _get_writer(file_or_filename, enc_lower) as write:if method == "xml" and (xml_declaration or(xml_declaration is None andenc_lower not in ("utf-8", "us-ascii", "unicode"))):declared_encoding = encodingif enc_lower == "unicode":# Retrieve the default encoding for the xml declarationimport localedeclared_encoding = locale.getpreferredencoding()write("<?xml version='1.0' encoding='%s'?>\n" % (declared_encoding,))if method == "text":_serialize_text(write, self._root)else:qnames, namespaces = _namespaces(self._root, default_namespace)serialize = _serialize[method]serialize(write, self._root, qnames, namespaces,short_empty_elements=short_empty_elements)

可能这是ElementTree在设计初为了方便在双引号中引用字串才将version和encoding改为用单引号展示。因为write()中没有复杂的间接依赖,可以直接将该方法复制到自己的工程里。为此,针对该处的修改就是重写ElementTree#write()。重新方案如下,先将源代码中的<?xml version='1.0' encoding='%s'?> 替换成 <?xml version=\"1.0\" encoding=\"%s\"?>。

同时针对提示引用缺失的方法,增加ElementTree前缀来指明调用路径。这样就可以保证整个write()也可以在自己的工程中被执行。修改后的代码如下:

def fix_write(self, file_or_filename,encoding=None,xml_declaration=None,default_namespace=None,method=None, *,short_empty_elements=True):if not method:method = "xml"elif method not in ElementTree._serialize:raise ValueError("unknown method %r" % method)if not encoding:if method == "c14n":encoding = "utf-8"else:encoding = "us-ascii"enc_lower = encoding.lower()with ElementTree._get_writer(file_or_filename, enc_lower) as write:if method == "xml" and (xml_declaration or(xml_declaration is None andenc_lower not in ("utf-8", "us-ascii", "unicode"))):declared_encoding = encodingif enc_lower == "unicode":# Retrieve the default encoding for the xml declarationimport localedeclared_encoding = locale.getpreferredencoding()write("<?xml version=\"1.0\" encoding=\"%s\"?>\n" % (declared_encoding,))if method == "text":ElementTree._serialize_text(write, self._root)else:qnames, namespaces = ElementTree._namespaces(self._root, default_namespace)serialize = ElementTree._serialize[method]serialize(write, self._root, qnames, namespaces,short_empty_elements=short_empty_elements)

修改后,将原来调用ElementTree#write()的地方改成使用fix_write即可,同时不要忘了,将当前工程的elementTree对象作为第一入参穿进去。修改后的运行结果就会发现没有额外的格式变更了。

def update_fix():tree = ET.parse('element_test.xml')root = tree.getroot()messages = root.findall('message')messages[0].text = "no, it's so cold,let's take a shower"fix_write(tree, 'element_test_update_fix.xml', encoding="utf-8", xml_declaration=True)

这篇关于Python往事:ElementTree的单引号之谜的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/505237

相关文章

Python版本信息获取方法详解与实战

《Python版本信息获取方法详解与实战》在Python开发中,获取Python版本号是调试、兼容性检查和版本控制的重要基础操作,本文详细介绍了如何使用sys和platform模块获取Python的主... 目录1. python版本号获取基础2. 使用sys模块获取版本信息2.1 sys模块概述2.1.1

一文详解Python如何开发游戏

《一文详解Python如何开发游戏》Python是一种非常流行的编程语言,也可以用来开发游戏模组,:本文主要介绍Python如何开发游戏的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录一、python简介二、Python 开发 2D 游戏的优劣势优势缺点三、Python 开发 3D

Python函数作用域与闭包举例深度解析

《Python函数作用域与闭包举例深度解析》Python函数的作用域规则和闭包是编程中的关键概念,它们决定了变量的访问和生命周期,:本文主要介绍Python函数作用域与闭包的相关资料,文中通过代码... 目录1. 基础作用域访问示例1:访问全局变量示例2:访问外层函数变量2. 闭包基础示例3:简单闭包示例4

Python实现字典转字符串的五种方法

《Python实现字典转字符串的五种方法》本文介绍了在Python中如何将字典数据结构转换为字符串格式的多种方法,首先可以通过内置的str()函数进行简单转换;其次利用ison.dumps()函数能够... 目录1、使用json模块的dumps方法:2、使用str方法:3、使用循环和字符串拼接:4、使用字符

Python版本与package版本兼容性检查方法总结

《Python版本与package版本兼容性检查方法总结》:本文主要介绍Python版本与package版本兼容性检查方法的相关资料,文中提供四种检查方法,分别是pip查询、conda管理、PyP... 目录引言为什么会出现兼容性问题方法一:用 pip 官方命令查询可用版本方法二:conda 管理包环境方法

基于Python开发Windows自动更新控制工具

《基于Python开发Windows自动更新控制工具》在当今数字化时代,操作系统更新已成为计算机维护的重要组成部分,本文介绍一款基于Python和PyQt5的Windows自动更新控制工具,有需要的可... 目录设计原理与技术实现系统架构概述数学建模工具界面完整代码实现技术深度分析多层级控制理论服务层控制注

pycharm跑python项目易出错的问题总结

《pycharm跑python项目易出错的问题总结》:本文主要介绍pycharm跑python项目易出错问题的相关资料,当你在PyCharm中运行Python程序时遇到报错,可以按照以下步骤进行排... 1. 一定不要在pycharm终端里面创建环境安装别人的项目子模块等,有可能出现的问题就是你不报错都安装

Python打包成exe常用的四种方法小结

《Python打包成exe常用的四种方法小结》本文主要介绍了Python打包成exe常用的四种方法,包括PyInstaller、cx_Freeze、Py2exe、Nuitka,文中通过示例代码介绍的非... 目录一.PyInstaller11.安装:2. PyInstaller常用参数下面是pyinstal

Python爬虫HTTPS使用requests,httpx,aiohttp实战中的证书异步等问题

《Python爬虫HTTPS使用requests,httpx,aiohttp实战中的证书异步等问题》在爬虫工程里,“HTTPS”是绕不开的话题,HTTPS为传输加密提供保护,同时也给爬虫带来证书校验、... 目录一、核心问题与优先级检查(先问三件事)二、基础示例:requests 与证书处理三、高并发选型:

Python中isinstance()函数原理解释及详细用法示例

《Python中isinstance()函数原理解释及详细用法示例》isinstance()是Python内置的一个非常有用的函数,用于检查一个对象是否属于指定的类型或类型元组中的某一个类型,它是Py... 目录python中isinstance()函数原理解释及详细用法指南一、isinstance()函数