[英]pretty_print option in tostring not working in lxml
我正在嘗試在XML中使用tostring方法來獲取XML的“漂亮”版本作為字符串。 lxml站點上的示例顯示了此示例:
>>> import lxml.etree as etree
>>> root = etree.Element("root")
>>> print(root.tag)
root
>>> root.append( etree.Element("child1") )
>>> child2 = etree.SubElement(root, "child2")
>>> child3 = etree.SubElement(root, "child3")
>>> print(etree.tostring(root, pretty_print=True))
<root>
<child1/>
<child2/>
<child3/>
</root>
但是我的輸出,運行那些確切的行是:
b'<root>\n <child1/>\n <child2/>\n <child3/>\n</root>\n'
我安裝的lxml版本是否有錯誤? 從教程中逐字逐句的單詞似乎很奇怪。
字符串前面的b
標志顯示它是一個字節字符串 。 要將其打印為unicode字符串(這是Python字符串的典型編碼),您可以執行以下操作:
print(etree.tostring(root,pretty_print=True).decode())
或者etree.tostring
有一個標志,允許您設置編碼,因此:
print(etree.tostring(root,pretty_print=True,encoding='unicode'))
無論哪種方式都適合我。 這里有關於Byte Strings和Strings的更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.