Inno Setup: Save XML document with indentation

时间:2016-04-04 16:29:58

标签: xml inno-setup

I'm trying to add a new node to XML file in Inno Setup. The node added correctly but the newline before the next tag is removed or no newline added. Here is my adding node code:

NewNode := XMLDoc.createElement('Test');
XMLDoc.setProperty('SelectionLanguage', 'XPath');
RootNode := XMLDoc.selectSingleNode('//Configuration/AppSettings');
RootNode.appendChild (NewNode);
RootNode.lastChild.text :='New Node';

Here is my XML file:

<Configuration>
    <AppSettings Name="General Settings">
        <StartTime/>
        <StopTime/>
        <TimeBetweenTests>30</TimeBetweenTests>
        <Port>600</Port>
        <Test>New Node</Test></AppSettings>
</Configuration>

I was expecting the tag

</AppSettings>

to stay in the newline as it was before the addition of the new node. How could I add a newline to keep the format more readable?

1 个答案:

答案 0 :(得分:2)

You can use MXXMLWriter class for the formatting:

procedure SaveXmlDocumentWithIndent(XmlDocument: Variant; FileName: string);
var
  Writer: Variant;
  Reader: Variant;
  FSO: Variant;
  TextStream: Variant;
begin
  Writer := CreateOleObject('Msxml2.MXXMLWriter');
  Reader := CreateOleObject('MSXML2.SAXXMLReader');
  FSO := CreateOleObject('Scripting.FileSystemObject');
  TextStream := FSO.CreateTextFile(FileName, True);
  Writer.Indent := True;
  Writer.OmitXMLDeclaration := True;
  Reader.ContentHandler := Writer;
  Reader.Parse(XmlDocument);
  TextStream.Write(Writer.Output);
  TextStream.Close();
end;

Credits: @cheeso's answer to How can I save an MSXML2.DomDocument with indenting?
I've just re-implemented his JavaScript code in Pascal Script.


The above solution will reformat complete XML document according to the liking of the MXXMLWriter class.

If you want to preserve some format of your choice, you have to implement it explicitly by adding the indentation you want.

To add a new line (#13#10 = CRLF) after the added node and (re)indent the closing parent tag with a tab character (#9), use:

RootNode.appendChild(XMLDoc.createTextNode(#13#10#9));