[fpc-pascal] XML read

Marcos Douglas md at delfire.net
Wed Jun 15 17:14:12 CEST 2011


On Tue, Jun 14, 2011 at 10:28 AM, Bart <bartjunk64 at gmail.com> wrote:
>
> My XmlToList procedure is based upon the XmlToTree example in the wiki.
>
> There are no memory leaks in my code (checked it with heaptrace).

Hi Bart,
Below is my "simple way" to get all <Text> for each <Page>:

----------------------------------------------------------------------------
program t_xml;

{$mode objfpc}{$H+}

uses
  Classes, sysutils, dom, XMLRead;

procedure ProcessPage(ANode: TDOMNode; APageNo: Integer);
var
  Node: TDOMNode;
begin
  if not Assigned(ANode) then
    Exit;
  Node := ANode.FirstChild;
  while Assigned(Node) do
  begin
    if Node.CompareName('Text') = 0 then
    begin
      writeln(Node.TextContent); // << do anything...
    end;
    Node := Node.NextSibling;
    ProcessPage(Node, APageNo);
  end;
end;

procedure ProcessNodes(ANode: TDOMNode);
var
  Node: TDOMNode;
  PageNo: Integer;
begin
  if not Assigned(ANode) then
    Exit;
  Node := ANode.FirstChild;
  while Assigned(Node) do
  begin
    if Node.CompareName('Page') = 0 then
    begin
      PageNo := StrToInt(Node.Attributes.GetNamedItem('number').NodeValue);
      ProcessPage(Node, PageNo);
    end;
    Node := Node.NextSibling;
    ProcessNodes(Node);
  end;
end;

var
  Doc: TXMLDocument;

begin
  ReadXMLFile(Doc, 'cc.xml');
  try
    ProcessNodes(Doc);
  finally
    Doc.Free;
  end;

end.
----------------------------------------------------------------------------

Thanks for you example!
BTW, I could not use FindNode('Pages'). Looks like is broke, isn't?

Marcos Douglas



More information about the fpc-pascal mailing list