简体   繁体   English

Python 不会将 \r\n 写入 XML 文件

[英]Python won't write \r\n to XML file

I am using python to generate XML files.我正在使用 python 生成 XML 个文件。 The XML files have attributes that require \r\n to denote a line break (regular \n will not work for this application). XML 文件具有需要\r\n表示换行符的属性(常规\n不适用于此应用程序)。 Here's an example of the XML file I am trying to generate:这是我尝试生成的 XML 文件的示例:

<root>
    <tag attrib="multiple&#13;&#10;lines&#13;&#10;here"></tag>
</root>

Note the &#10;注意&#10; is the XML escape character encoding for \n and &#13;是 XML 转义字符编码\n&#13; is \r .\r

Here is my python code to generate this XML file:这是我的 python 代码,用于生成这个 XML 文件:

import xml.etree.ElementTree as ET


root = ET.Element('root')
tag = ET.SubElement(root, 'tag')
tag.set('attrib', 'multiple\r\nlines\r\nhere')

xml_file = 'test.xml'
tree = ET.ElementTree(root)
tree.write(xml_file)

Output: <root><tag attrib="multiple&#10;lines&#10;here" /></root> Output: <root><tag attrib="multiple&#10;lines&#10;here" /></root>

It is clear that the \r is stripped from the output XML. How can I add \r\n to my XML files?很明显, \r是从 output XML 中删除的。如何将\r\n添加到我的 XML 文件中?

After a few hours of searching for this, I eventually found that it is a bug in the XML package (See https://bugs.python.org/issue39011 ).经过几个小时的搜索,我最终发现它是 XML package 中的一个错误(参见https://bugs.python.org/issue39011 )。 From what I can tell on the cpython github page, this is fixed on Python 3.9, but not any earlier versions.据我所知,在 cpython github 页面上,这是在 Python 3.9 上修复的,但不是任何早期版本。 For versions without the bug fix, here is a workaround I've used:对于没有错误修复的版本,这里是我使用的解决方法:

with open(xml_file, 'r') as f:
    lines = f.read()

with open(xml_file, 'w') as f:
    lines = f.write(lines.replace('&#10;', '&#13;&#10;')

After you create an XML file without \r\n , you open it and replace any occurrences of \n in the attributes with \r\n .在创建不带\r\n的 XML 文件后,打开它并将属性中出现的任何\n替换为\r\n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM