How to write an XML file without header in Python?

2020-05-27 04:39发布

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

<?xml version="1.0"?>

[...]

While this is perfectly legal XML code, and it's even recommended to use the header, I'd like to get rid of it as one of the programs I'm working with has problems here.

I can't seem to find the appropriate option in xml.dom.minidom, so I wondered if there are other packages which do allow to neglect the header.

Cheers,

Nico

标签: python xml
7条回答
相关推荐>>
2楼-- · 2020-05-27 05:40

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.

查看更多
登录 后发表回答