我正在将xml写入字符串,下面是包含声明的代码
updatedxml = ET.tostring(root, encoding="utf8", method="xml").decode()输出(在声明后添加Newline)
<?xml version='1.0' encoding='utf8'?>
<manifest>...</manifest>updatedxml在解析为JSON之前使用json dumps进行序列化。
print(json.dumps(updatedxml))在输出中有一个"\n“,有什么能摆脱它的节能型方法吗?
"<?xml version='1.0' encoding='utf8'?>\n<manifest>...</manifest>"发布于 2021-09-15 10:20:31
因此,之所以会发生这种情况,是因为下面是toString方法的toString实现,它内部调用写方法,如下所示:
def tostring(element, encoding=None, method=None, *, short_empty_elements=True):
stream = io.StringIO() if encoding == 'unicode' else io.BytesIO()
ElementTree(element).write(stream, encoding, method=method, short_empty_elements=short_empty_elements)
return stream.getvalue()
def write(self, file_or_filename, encoding=None, xml_declaration=None, default_namespace=None, method=None, *,
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 and enc_lower not in ("utf-8", "us-ascii", "unicode"))):
declared_encoding = encoding
if enc_lower == "unicode":
# Retrieve the default encoding for the xml declaration
import locale
declared_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)您可以看到,"\n“是由这个写方法编写的。
最简单的方法是之后删除"\n“。
print("".join(json.dumps(updatedxml).split("\\n")))如果只想替换"\n“的第一个实例,请执行以下操作:
print(json.dumps(updatedxml).replace("\\n", "", 1))发布于 2021-09-15 10:27:53
如果要删除所有换行符,只需使用python的string.replace()
print(json.dumps(updatedxml).replace("\n", ""))若要删除<manifest>之前的换行符,但保留所有其他换行符,请获取它的索引,然后从输出中排除该字符
dump = json.dumps(updatedxml)
idx = dump.index("\n<manifest>")
print(dump[:idx] + dump[idx+1:])既然你要求用节奏曲的方法,我想你可以使用列表理解,尽管上面的内容可能更快,也更容易阅读。
dump = json.dumps(updatedxml)
print("".join([char for i, char in enumerate(dump) if i != dump.index("\n<manifest>")]))https://stackoverflow.com/questions/69191145
复制相似问题