Search code examples
xmlpowershellinno-setuppascalscript

Deleting content of XML element in Inno Setup


I am trying to convert a PowerShell script to Inno Setup Pascal Script code.

$regularExpression=@'
(?ms)^(\s*  <ReportParametersLayout>\s*?\r?\n).*?\r?\n(\s*  </ReportParametersLayout>\s*)
'@

Foreach ($file in $files) {
    $text = (Get-Content $file) | Out-String 
    $text -replace $regularExpression, '$1$2' | Set-Content -Encoding UTF8 $file
}

This part of PowerShell script deletes content between ReportParametersLayout element of RDL file with regular expressions for converting SQL Server 2016 Reports to SQL Server 2008.

<Report>
  ...
  <ReportParametersLayout>
    <GridLayoutDefinition>
      <NumberOfColumns>4</NumberOfColumns>
      <NumberOfRows>3</NumberOfRows>
      <CellDefinitions>
        <CellDefinition>
          <ColumnIndex>0</ColumnIndex>
          <RowIndex>0</RowIndex>
          <ParameterName>StartDate</ParameterName>
        </CellDefinition>
        <CellDefinition>
          <ColumnIndex>1</ColumnIndex>
          <RowIndex>0</RowIndex>
          <ParameterName>EndDate</ParameterName>
        </CellDefinition>
      </CellDefinitions>
    </GridLayoutDefinition>
  </ReportParametersLayout>
  ...
<Report>

What should I do for deleting content between XML element of ReportParametersLayout to reach this outcome in Code Section?

<Report>
  ...
  <ReportParametersLayout>
  </ReportParametersLayout>
  ...
</Report>

Solution

  • The following code will delete nodes selected by XPath:

    procedure DeleteNodes(FileName, Path: string);
    var
      XMLDocument: Variant;
      XMLNodeList: Variant;
      Index: Integer;
    begin
      XMLDocument := CreateOleObject('Msxml2.DOMDocument.6.0');
      try
        XMLDocument.async := False;
        XMLDocument.load(FileName);
        if XMLDocument.parseError.errorCode <> 0 then
        begin
          MsgBox('The XML file could not be parsed. ' +
            XMLDocument.parseError.reason, mbError, MB_OK)
        end
          else
        begin
          XMLDocument.setProperty('SelectionLanguage', 'XPath');
          XMLNodeList := XMLDocument.selectNodes(Path);
          for Index := 0 to XMLNodeList.length - 1 do
          begin
            XMLNodeList.item[Index].parentNode.removeChild(XMLNodeList.item[Index]);
          end;
          XMLDocument.save(FileName);
        end;
      except
        MsgBox('An error occured!' + #13#10 + GetExceptionMessage, mbError, MB_OK);
      end;
    end;
    

    You can use the function like this to delete all child nodes of all <ReportParametersLayout> tags:

    DeleteNodes('C:\some\path\my.xml', '//ReportParametersLayout/*');