我正在尝试使用 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
标志向您显示它是 byte string .要将其打印为 unicode 字符串(这是 Python 字符串的典型编码),您可以执行以下操作:
print(etree.tostring(root,pretty_print=True).decode())
或 etree.tostring
有一个允许您设置编码的标志,因此:
print(etree.tostring(root,pretty_print=True,encoding='unicode'))
两种方式都适合我。这是有关 Byte Strings 的更多信息和 Strings
关于python - tostring 中的 pretty_print 选项在 lxml 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22718101/