python 如何查看 lxml 元素的文本表示?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1567903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:36:11  来源:igfitidea点击:

How can I view a text representation of an lxml element?

pythonxmllxml

提问by Geo

If I'm parsing an XML document using lxml, is it possible to view a text representation of an element? I tried to do :

如果我使用 lxml 解析 XML 文档,是否可以查看元素的文本表示?我试图做:

print repr(node)

but this outputs

但这输出

<Element obj at b743c0>

What can I use to see the node like it exists in the XML file? Is there some to_xmlmethod or something?

我可以用什么来查看 XML 文件中存在的节点?有to_xml什么方法什么的吗?

回答by Jeff Ober

From http://lxml.de/tutorial.html#serialisation

来自http://lxml.de/tutorial.html#serialisation

>>> root = etree.XML('<root><a><b/></a></root>')

>>> etree.tostring(root)
b'<root><a><b/></a></root>'

>>> print(etree.tostring(root, xml_declaration=True))
<?xml version='1.0' encoding='ASCII'?>
<root><a><b/></a></root>

>>> print(etree.tostring(root, encoding='iso-8859-1'))
<?xml version='1.0' encoding='iso-8859-1'?>
<root><a><b/></a></root>

>>> print(etree.tostring(root, pretty_print=True))
<root>
  <a>
    <b/>
  </a>
</root>