代码之家  ›  专栏  ›  技术社区  ›  pierroz

使用toprettyxml()时新行出现问题

  •  10
  • pierroz  · 技术社区  · 16 年前

    我目前正在使用 toprettyxml() xml.dom newl toprettyxml(newl='\n')

    f = open(filename, 'w')
    f.write(dom1.toprettyxml(encoding='UTF-8'))
    f.close()
    

    <params>
    
    
        <param name="Level" value="#LEVEL#"/>
    
    
        <param name="Code" value="281"/>
    
    
    </params>
    

    6 回复  |  直到 6 年前
        1
  •  15
  •   Community Mohan Dere    9 年前

    我找到了另一个很好的解决方案:

    f = open(filename, 'w')
    dom_string = dom1.toprettyxml(encoding='UTF-8')
    dom_string = os.linesep.join([s for s in dom_string.splitlines() if s.strip()])
    f.write(dom_string)
    f.close()
    

    上述解决方案基本上从toprettyxml()生成的dom_string中删除了不需要的换行符。

    输入来自-> What's a quick one-liner to remove empty lines from a python string?

        2
  •  13
  •   xverges IrocD    13 年前
        3
  •  4
  •   OndrejC    12 年前

    toprettyxml(newl='') 在Windows上为我工作。

        4
  •  3
  •   Link64    8 年前

    这是一个很老的问题,但我想我知道问题是什么:

    Minidoms的漂亮印刷有一种非常直接的方法。它只是添加您指定为参数的字符。这意味着,如果字符已经存在,它将复制它们。

    <parent>
       <child>
          Some text
       </child>
    </parent>
    

    dom中已经有换行符和缩进。这些节点被minidom视为文本节点,当您将其解析为dom对象时,它们仍然存在。

    如果现在继续将dom对象转换为XML字符串,则这些文本节点仍将存在。这意味着新行字符和缩进制表符仍然存在。现在使用漂亮的打印,只需添加 新线路和 选项卡。这就是为什么在这种情况下根本不使用漂亮的打印或指定 newl='' 将产生所需的输出。

    newl='\r\n' addindent='\t' 结果会很漂亮。

    TL;DR缩进和换行保留在解析过程中,漂亮的打印只会增加更多内容

        5
  •  2
  •   felixhummel    16 年前

    如果你不介意安装新的软件包,可以尝试beautifulsoup。我对它有很好的体验 xml prettyfier .

        6
  •  0
  •   Naveed Rasheed    7 年前

    实施的关键如下:

    1. 使用dom.toprettyxml()
    2. 根据您的要求添加新行和选项卡。

    ~

    import os
    import re
    import xml.dom.minidom
    import sys
    
    class XmlTag:
        opening = 0
        closing = 1
        self_closing = 2
        closing_tag = "</"
        self_closing_tag = "/>"
        opening_tag = "<"
    
    def to_pretty_xml(xml_file_path):
        pretty_xml = ""
        space_or_tab_count = "  " # Add spaces or use \t
        tab_count = 0
        last_tag = -1
    
        dom = xml.dom.minidom.parse(xml_file_path)
    
        # get pretty-printed version of input file
        string_xml = dom.toprettyxml(' ', os.linesep)
    
        # remove version tag
        string_xml = string_xml.replace("<?xml version=\"1.0\" ?>", '')
    
        # remove empty lines and spaces
        string_xml = "".join(string_xml.split())
    
        # move each tag to new line
        string_xml = string_xml.replace('>', '>\n')
    
        for line in string_xml.split('\n'):
            if line.__contains__(XmlTag.closing_tag):
    
                # For consecutive closing tags decrease the indentation
                if last_tag == XmlTag.closing:
                    tab_count = tab_count - 1
    
                # Move closing element to next line
                if last_tag == XmlTag.closing or last_tag == XmlTag.self_closing:
                    pretty_xml = pretty_xml + '\n' + (space_or_tab_count * tab_count)
    
                pretty_xml = pretty_xml + line
                last_tag = XmlTag.closing
    
            elif line.__contains__(XmlTag.self_closing_tag):
    
                # Print self closing on next line with one indentation from parent node
                pretty_xml = pretty_xml + '\n' + (space_or_tab_count * (tab_count+1)) + line
                last_tag = XmlTag.self_closing
    
            elif line.__contains__(XmlTag.opening_tag):
    
                # For consecutive opening tags increase the indentation
                if last_tag == XmlTag.opening:
                    tab_count = tab_count + 1
    
                # Move opening element to next line
                if last_tag == XmlTag.opening or last_tag == XmlTag.closing:
                    pretty_xml = pretty_xml + '\n' + (space_or_tab_count * tab_count)
    
                pretty_xml = pretty_xml + line
                last_tag = XmlTag.opening
    
        return pretty_xml
    
    pretty_xml = to_pretty_xml("simple.xml")
    
    with open("pretty.xml", 'w') as f:
        f.write(pretty_xml)
    
        7
  •  0
  •   n-a-t-e    5 年前

    dom = xml.dom.minidom.parseString(xml_string)
    
    pretty_xml_as_string = dom.toprettyxml(newl='').replace("\n\n", "\n")
    
        8
  •  -1
  •   Will McCutchen    16 年前

    您是否正在Windows上查看生成的文件?如果是这样,请尝试使用 toprettyxml(newl='\r\n') .