Convert an INI file to XML (Views: 101)


INI was the old way to store settings (outside the registry), now everything is XML. This routine will convert an INI file into an XML node of a document.


An XML node is part of an XML Document.  So if you have a new XMLDocument then just add a single node (AddChild) and that is the DocumentNode, then you could pass the DocumentNode to this routine.  If you pass in different Nodes then you could store multiple INI files in the same XML document, even if they have section and value name collisions.  The AsAttributes parameter determines if the values are stored as Attributes (default) or sub-nodes.  

uses XMLIntf, XMLDoc, INIFiles;

procedure INI2XML(const pINIFileName: string; const pXML: IXMLNode;
  const AsAttributes: Boolean = true);
  lINIFile: TIniFile;
  lSections, lItems: TStringList;
  iSections, iItems: integer;
  lNode: IXMLNode;
  lINIFile := TIniFile.Create(pINIFileName);
    lSections := TStringList.Create;
      lItems := TStringList.Create;


        for iSections := 0 to pred(lSections.Count) do
          lINIFile.ReadSection(lSections[iSections], lItems);
          lNode := pXML.AddChild(StringReplace(lSections[iSections], ' ', '',
          for iItems := 0 to pred(lItems.Count) do
            if AsAttributes then
              lNode.Attributes[lItems[iItems]] :=
                lINIFile.ReadString(lSections[iSections], lItems[iItems], '')
              lNode.AddChild(lItems[iItems]).Text :=
                lINIFile.ReadString(lSections[iSections], lItems[iItems], '');
          lNode := nil;

      finally lItems.Free;
    finally lSections.Free;
  finally lINIFile.Free;

<< Back to main page