Mirror

Easy Parsing an XML File (Views: 100)

Problem/Question/Abstract:

In modern times, a configuration file has to be an XML standard so you want to parse that file to get the elements from corresponding nodes.

Answer:

First you have to import the Type library. This will create a wrapper class for that component and all you have to do is to name it in uses in your unit.
I used msxml.dll(Version 2.0) to install the XML parsing components in the IDE through the Import Type Library option.

See article for more details: Importing XML DOM Parser in Delphi

Second we produce a simple XML file like a configuration file:
(Name the file myconfig.xml)





TrueSoft
superPath
MaxMin




maXml
kylix02
carpeDiem




Third we build the procedure that parses 3 elements and assign it to strings:

myname, mypath, myuser: string[255];

The accID and idNr are just to make the procedure more flexible for permissions and node navigation. The whole procedure goes like this:

Find the file myconfig.xml
Create the interface pointer xmlDoc
Load the XML file
Check the error handling with xmlDoc.parseError
Select the node
Check if it has childs
Get the nodelist and assign the elements to strings


procedure TForm1.parseXML;
var
SRec1: TSearchRec;
accID: boolean;
idNr: byte;
myXMLpath: string;
xmlDoc: IXMLDomDocument2;
xmlnode: IXMLDomNode;
xmlnodelist: IXMLDomNodeList;
myname, mypath, myuser: string[255];
begin
accID := true;
idNr := 1;
myXMLpath := extractFilePath(Application.ExeName);
if FindFirst(myXMLpath + 'myconfig.xml', faAnyFile, SRec1) = 0 then
begin
xmlDoc := CoDomDocument30.Create;
xmlDoc.validateOnParse := True;
xmlDoc.async := False;
xmlDoc.load(myXMLpath + 'myconfig.xml');
if xmlDoc.parseError.errorCode = 0 then
begin
if accID then
begin
xmlDoc.setProperty('SelectionLanguage', 'XPath');
xmlnode := xmlDoc.selectSingleNode('//databases/database
[@db = '+''''+' InterBase '+''''+ ']');
if xmlnode.hasChildNodes then
begin
if (idNR <= xmlnode.childNodes.length) and (idNR > 0) then
begin
xmlnodelist := xmlnode.childNodes.item[(idNR - 1)].selectNodes
('name');
if xmlnodelist.length <> 0 then
myname := xmlnode.childNodes.item[(idNR - 1)].selectNodes('name').item
[0].text;
xmlnodelist := xmlnode.childNodes.item[(idNR - 1)].selectNodes
('path');
if xmlnodelist.length <> 0 then
mypath := xmlnode.childNodes.item[(idNR - 1)].selectNodes('path').item
[0].text;
xmlnodelist := xmlnode.childNodes.item[(idNR - 1)].selectNodes
('user');
if xmlnodelist.length <> 0 then
myuser := xmlnode.childNodes.item[(idNR - 1)].selectNodes('user').item
[0].text;
end;
end
else
showmessage('no XML Childs');
end
else
showmessage('no permission');
end
else
begin
showmessage('load XML error');
xmlDoc := nil;
FindClose(SRec1)
end;
end
else
showmessage('no XML file');
end;


<< Back to main page