xml indentation

lean pol picture lean pol · Dec 27, 2010 · Viewed 7.4k times · Source

I am writing an xml file using the xmlwriter api of libxml2.

when I open the file using notepad, the indentation isn't right.

does anybody know how to fix it?

thanks a whole lot.

Answer

Thanatos picture Thanatos · Dec 27, 2010

I'm going on a bit of a limb here, but I'll say that by "the indentation isn't right" you mean it isn't indented at all.

libxml2, by default, won't indent your XML file, because in XML, whitespace (including that used for indentation) is significant data. That is, this XML file:

<root>
    <foo>Bar</foo>
</root>

is semantically different from:

<root><foo>Bar</foo></root>

... in that the two character data pieces from the first XML file could be significant to you, the programmer, so, XML leaves them in there when reading the file, and will not output them (unless instructed) when writing.

That said, this is an oft-abused bit of XML. Most XML I've seen is, sadly, indented. libxml2 has options for automatically outputting the indentation when writing, and removing it when reading, but note: there are some caveats to this: it might get it wrong. The docs say more.

I think this function might help you (I've never actually used this myself :-) ), if you want it to indent for you: xmlTextWriterSetIndent

Heed the warning here: libxml2 FAQ

And the information here: XML Specification