【问题标题】:lxml: pretty_print option in tostring not working correctly after newline symbol [duplicate]lxml:tostring中的pretty_print选项在换行符后无法正常工作[重复]
【发布时间】:2016-07-16 23:29:53
【问题描述】:

在符号 '\n' 之后,pretty_print 被忽略。 例如:

import lxml.etree as etree

strs = ["<root>\n<e1/><e2/></root>",
  "<root><e1/><e2/></root>"]

for str in strs:
 xml = etree.fromstring(str)
 print etree.tostring(xml, pretty_print=True)

输出是:

<root>
<e1/><e2/></root>

<root>
  <e1/>
  <e2/>
</root>

两个字符串都是有效的 xml。 第一个字符串有符号 '\n' 并且在这个符号之后会忽略 pretty_print。

是和 lxml 的错误还是我需要特殊操作来进行漂亮的格式化?

【问题讨论】:

    标签: python lxml pretty-print


    【解决方案1】:

    谢谢你,科利

    这里解释了这种行为的原因: http://lxml.de/FAQ.html#why-doesn-t-the-pretty-print-option-reformat-my-xml-output

    正确的代码是:

    import lxml.etree as etree
    
    strs = ["<root>\n<e1/><e2/></root>",
        "<root><e1/><e2/></root>"]
    
    parser = etree.XMLParser(remove_blank_text=True)
    for str in strs:
        xml = etree.fromstring(str, parser=parser)
        print etree.tostring(xml, pretty_print=True)
    
        # or for Python 3.x
        print(etree.tostring(xml, pretty_print=True).decode())
        # here I assume utf-8 encoding
    

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      • 2014-10-31
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多