How to write an XML file without header in Python?

后端 未结 7 1290
盖世英雄少女心
盖世英雄少女心 2021-02-06 01:28

when using Python\'s stock XML tools such as xml.dom.minidom for XML writing, a file would always start off like

<

7条回答
  •  不知归路
    2021-02-06 01:48

    You might be able to use a custom file-like object which removes the first tag, e.g:

    class RemoveFirstLine:
        def __init__(self, f):
            self.f = f
            self.xmlTagFound = False
    
        def __getattr__(self, attr):
            return getattr(self, self.f)
    
        def write(self, s):
            if not self.xmlTagFound:
                x = 0 # just to be safe
                for x, c in enumerate(s):
                    if c == '>':
                        self.xmlTagFound = True
                        break
                self.f.write(s[x+1:])
            else:
                self.f.write(s)
    
    ...
    f = RemoveFirstLine(open('path', 'wb'))
    Node.writexml(f, encoding='UTF-8')
    

    or something similar. This has the advantage the file doesn't have to be totally rewritten if the XML files are fairly large.

提交回复
热议问题