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

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

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

    toprettyxml() 委员会的职能 xml.dom Python脚本中的模块,我在换行方面遇到了一些问题。 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>
    

    有人知道问题来自何处,我如何使用它吗? 仅供参考,我正在使用Python 2.6.1

    6 回复  |  直到 5 年前
        1
  •  15
  •   Community CDub    8 年前

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

    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_字符串中删除不需要的换行符。

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

        2
  •  13
  •   xverges IrocD    12 年前

    toprettyxml() newl 参数显示添加的行太多。不仅如此,还添加了其他空格(当机器读取xml时可能会导致问题)。

    一些变通方法可在
    http://ronrothman.com/public/leftbraned/xml-dom-minidom-toprettyxml-and-silly-whitespace

        3
  •  4
  •   OndrejC    11 年前

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

        4
  •  3
  •   Link64    7 年前

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

    例如,如果您解析一个如下所示的XML文件:

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

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

    更多 新线和 更多 标签。这就是为什么在这种情况下根本不使用漂亮的打印或指定 newl=''

    但是,在脚本中生成dom时,文本节点将不存在,因此使用 newl='\r\n' addindent='\t'

        5
  •  2
  •   felixhummel    15 年前
        6
  •  0
  •   Naveed Rasheed    6 年前

    实施的关键如下:

    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    4 年前

    这为我在Python 3.6上提供了很好的XML,我还没有在Windows上尝试过:

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

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