【问题标题】:how to pretty_print xincluded file?如何漂亮打印 xincluded 文件?
【发布时间】:2020-07-13 11:03:43
【问题描述】:
from lxml import etree
tree = etree.parse("part_000001.xml")
tree.xinclude()
string = etree.tostring(tree, pretty_print=True)

print(string)

我正在尝试 pretty_print 一个 XML 文件,我的 pretty_print 选项在控制台中打开(%%pprint 打开和关闭它),但终端仍然没有插入实际的换行符,而是 "\n " 包含在字符串中。

如何更改它以便实际插入换行符?

【问题讨论】:

    标签: python xml io


    【解决方案1】:

    你可以试试BeautifulSoup 并使用 prettify() 你可以这样格式化你的代码:

    from bs4 import BeautifulSoup
    
    #you will FIRST need to read the xml file to pass into BS as shown below
    
    content = []
    with open("part_000001.xml", "r") as file:
        content = file.readlines()
        content = "".join(content)
        bs_content = bs(content, "lxml")
    
    print(bs_content.prettify())
    

    您可以在此here 上阅读更多信息。

    【讨论】:

      【解决方案2】:

      字节必须先转成字符串:

      string = etree.tostring(tree, pretty_print=True).decode("utf-8") #decode will convert bytes into string
      

      【讨论】:

        猜你喜欢
        • 2013-06-21
        • 2012-10-08
        • 1970-01-01
        • 2011-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-14
        相关资源
        最近更新 更多