我正在寫一個xml到一個字串,這是我的代碼,包括宣告
。updatedxml = ET.tostring(root, encoding="utf8"/span>, method="xml"/span>).decode()
輸出(在宣告后添加了換行)
<?xml version='1.0' encoding='utf8'? >
<manifest>...</manifest>
updatedxml后來使用json dumps進行序列化,然后決議為JSON
print(json.dumps(updatedxml)
并且在輸出中出現了一個" "在輸出中,有什么pythonic方法可以去掉它嗎?
"<?xml version='1.0' encoding='utf8'?>/span>
<manifest>...</manifest> "
uj5u.com熱心網友回復:
如果你想洗掉所有的換行,你可以直接使用python的string.replace()
print(json.dumps(updatexml).replace("
", " "))
要洗掉<manifest>前的換行符,但保留所有其他的換行符,先獲取它的索引,然后從輸出中排除該字符
dump = json.dumps(upedxml)
idx = dump.index("
<manifest>")
print(dump[:idx] dump[idx 1:] )
既然你要求使用pythonic方法,我想你可以使用串列理解,盡管上面的方法可能更快,而且更容易閱讀。
dump = json.dumps(upedxml)
print(""/span>. join([char for i, char in enumerate(dump) if I != dump.index("
<manifest>")]))
uj5u.com熱心網友回復:
所以發生這種情況的原因是下面ElementTree實作的toString方法在內部呼叫了write方法,如下圖所示:
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"/span>
elif method not in _serialize:
raise ValueError("unknown method %r" % method)
if not encoding:
if method == "c14n"/span>:
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 是 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()
寫("<?xml version='1.0' encoding='%s'?>
"% (declared_encoding,))
if method == "text"/span>:
_serialize_text(write, self._root)
else:
qnames, namespaces = _namespaces(self._root, default_namespace)
序列化 = _serialize[方法]
serialize(write, self._root, qnames, namespaces, short_empty_elements=short_empty_elements)
你可以看到," "被這個write方法所寫入。
最簡單的方法是事后洗掉" "之后。
print(""/span>. join(json.dumps(updatedxml).split("n") )
如果你只想替換第一個實體的" "的第一個實體,那么請執行以下步驟:
print(json.dumps(updatedxml) 。 replace("/span>, "/span>, 1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/307712.html
標籤:
