0

I create XML documents by creating a full-blown in-memory DOM model and storing it to a file by using the IXMLDocument::save method. To format these documents, I use the trick with creating a text node consisting entirely of newline and tabs. This trick works well inside a node, but at the document level it fails. As a result, I get partially aligned documents like this:

<?xml version="1.0" encoding="UTF-8"?><!--Main Comment--><Root>
    <InputFile>
        <FileName>Part1</FileName>
        <FileDirectory>D:\Document Folder\Testing</FileDirectory>
    </InputFile>
    . . . . .
</Root>

Is there any other trick to insert a newline before the main comment and before the root node? I prefer a solution that is limited to C++ DOM interfaces and does not involve external tools or libraries.

Ilia
  • 425
  • 2
  • 10

1 Answers1

1

Here is XSLT based solution.

It is using a so called Identity Transform pattern.

The indent="yes" attribute will indent the entire XML.

XSLT

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="xml" indent="yes" encoding="utf-8" omit-xml-declaration="no"/>

   <xsl:strip-space elements="*"/>

   <xsl:template match="node()|@*">
      <xsl:copy>
         <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
   </xsl:template>
</xsl:stylesheet>
Yitzhak Khabinsky
  • 18,471
  • 2
  • 15
  • 21
  • Your solution would be good if it worked. First, it has the same problem as my original version: there are no line breaks before the main comment and before the root node. Second, even though it inserts line breaks before each subnode, it doesn't insert tabs and so there is no indentation. Perhaps, all this can be eliminated with a small fix in the .xslt file; I would appreciate it if you do. – Ilia Jun 28 '22 at 10:31
  • Please connect with me on LinkedIn – Yitzhak Khabinsky Jun 28 '22 at 11:56
  • I did a more thorough search and found a number of exactly the same complaints: When using MSXML, formatting with XSLT does put each subnode on separate line, but without indentation. So, this is a common problem and I'm not going to fight it now. Pretty formatting is nice to have, but my original solution is also acceptable to our users. But thank you anyway: knowing about XSLT transformations can be useful in other situations. – Ilia Jun 28 '22 at 14:21
  • Check it out: https://stackoverflow.com/questions/164575/msxml-from-c-pretty-print-indent-newly-created-documents – Yitzhak Khabinsky Jun 28 '22 at 15:51