tags:

views:

217

answers:

4

Hi,

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

A: 

Purists may not like to hear this, but I have found using an XML parser to generate XML to be overkill. Just generate it directly as strings. This also lets you generate files larger than you can keep in memory, which you can't do with DOM. Reading XML is another story.

bobmcn
This is fraught with pitfalls. Serialising XML is easier than parsing it, but it still requires considerable care to get right. Stuff like whitespace escaping in attribute values (to avoid normalisation on parsing), the `]]>` issue, splitting CDATA sections (especially if you need non-UTF-8 output), and above all the complexity of serialising namespaced DOMs. You *will* make mistakes and generate something that isn't well-formed XML. And then all the mean kids will laugh.
bobince
+3  A: 

Unfortunately minidom does not give you the option to omit the XML Declaration.

But you can always serialise the document content yourself by calling toxml() on the document's root element instead of the document. Then you won't get an XML Declaration:

xml= document.documentElement.toxml('utf-8')

...but then you also wouldn't get anything else outside the root element, such as the DOCTYPE, or any comments or processing instructions. If you need them, serialise each child of the document object one by one:

xml= '\n'.join(node.toxml('utf-8') for node in document.childNodes)

I wondered if there are other packages which do allow to neglect the header.

DOM Level 3 LS defines an xml-declaration config parameter you can use to suppress it. The only Python implementation I know of is pxdom, which is thorough on standards support, but not at all fast.

bobince
For the record, the LXML and Python 2.7 ElementTree APIs accept `xml_declaration=False` on `.write()` and both LXML and cElementTree are very fast.
ssokolow
A: 

If you're set on using minidom, just scan back in the file and remove the first line after writing all the XML you need.

Isaac Hodes
A: 

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.

David Morrissey