Tips&Tricks I trucchi del mestiere

 

Recuperare un file XML dal WEB

Il tip consente di agganciarsi ad un indirizzo Web e downloadare, in locale, il contenuto di un documento XML; i dati presenti in quest'ultimo saranno quindi formattati e inseriti in una ListBox appositamente configurata. Nell'esempio, il sito web dal quale reperire il file xml è segnato come http://www.localhost, mentre il file XML è identificato come index.xml.


unit Unit1;
interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, xmldom, XMLDoc, msxmldom, ComCtrls,
  StdCtrls, ExtCtrls, XMLIntf;

type
  TForm1 = class(TForm)
    lv: TListView;
    XMLDoc: TXMLDocument;
    pnlTop: TPanel;
    btnRefresh: TButton;
    procedure btnRefreshClick(Sender: TObject);

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation
{$R *.dfm}

uses ExtActns;

function DownloadURLFile(const URL_XML, File_Locale : TFileName) : boolean;
begin
  Result:=True;

  with TDownLoadURL.Create(nil) do
  try
    URL:=URL_XML;
    Filename:=File_Locale;
    try
      ExecuteTarget(nil);
    except
      Result:=False;
    end;
  finally
    Free;
  end;
end;

procedure TForm1.btnRefreshClick(Sender: TObject);
const
  URL_XML = 'http://localhost/index.xml';
var
  File_Locale : TFileName;

  StartItemNode : IXMLNode;
  ANode : IXMLNode;
  STitle, sDesc : widestring;
begin
 File_Locale := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName)) + 'temp.adpheadlines.xml';

  Screen.Cursor:=crHourglass;
  try
    if not DownloadURLFile(URL_XML, File_Locale)  then
    begin
      Screen.Cursor:=crDefault;
      Raise Exception.CreateFmt('Non è stato possibile connettersi al Web',[]);
      Exit;
    end;

    if not FileExists(File_Locale) then
    begin
      Screen.Cursor:=crDefault;
      raise exception.Create('Errore!');
      Exit;
    end;

    lv.Clear;

    XMLDoc.FileName := File_Locale;
    XMLDoc.Active:=True;
    StartItemNode:=XMLDoc.DocumentElement.ChildNodes.First.ChildNodes.FindNode('item');
    ANode := StartItemNode;
    repeat
      STitle := ANode.ChildNodes['titolo'].Text;
      sDesc := ANode.ChildNodes['descrizione'].Text;

      with LV.Items.Add do
      begin
        Caption := STitle;
        SubItems.Add(sDesc)
      end;

      ANode := ANode.NextSibling;
    until ANode = nil;
  finally
    DeleteFile(File_Locale);
    Screen.Cursor:=crDefault;
  end;
end;
end.