tostring中的pretty_print选项在lxml中不起作用 [英] pretty_print option in tostring not working in lxml

查看:73
本文介绍了tostring中的pretty_print选项在lxml中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在XML中使用tostring方法来获取XML的漂亮"版本作为字符串.lxml站点上的示例显示了以下示例:

I'm trying to use the tostring method in XML to get a "pretty" version of my XML as a string. The example on the lxml site shows this example:

>>> 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>

不过,我的输出结果是:

However my output, running those exact lines is:

b'<root>\n  <child1/>\n  <child2/>\n  <child3/>\n</root>\n'

我安装的lxml版本中是否存在错误?教程中的逐字示例似乎不起作用.

Is there a bug in the version of lxml I have installed? It seems odd the word for word example from the tutorial is not working.

推荐答案

字符串前面的 b 标志向您显示它是

the b flag in front of the string shows you that it's a byte string. To print that as a unicode string (which is the typical encoding for a Python string), you can do:

print(etree.tostring(root,pretty_print=True).decode())

etree.tostring 具有用于设置编码的标志,因此:

or etree.tostring has a flag that allows you to set the encoding, so:

print(etree.tostring(root,pretty_print=True,encoding='unicode'))

这两种方法都对我有效.以下是有关字节字符串

Either way works for me. Here's more information on Byte Strings and Strings

这篇关于tostring中的pretty_print选项在lxml中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆