delphi‎ > ‎

TXMLDocumentからXPathでIXMLNodeを取得する

2010/01/30 13:08 に いつかはちょうになる が投稿   [ 2010/01/30 13:42 に更新しました ]
面倒なのでクラスを拡張版と関数を用意しました。

関数版

function readXPath(AXML: TXMLDocument; ANode: IXMLNode; AXPath: String): IXMLNode;
var
  i,j: Integer;
  s,s2: String;
  n: IXMLNode;
begin
  j:=AnsiPos('/', AXPath);
  if (j=0) then
    begin
      j:=Length(AXPath)+1;
    end;
  s:=Copy(AXPath, 1,j-1);
  s2:=AXPath;
  Delete(s2, 1, j);
  if (AXML<>nil) then
    begin
      Result:=AXML.ChildNodes.FindNode(s);
    end
  else
    begin
      Result:=ANode.ChildNodes.FindNode(s);
    end;
  if (Result<>nil) and (s2<>'') then
    begin
      Result:=readXPath(nil, Result, s2);
    end;
end;

var
  xml: TXXMLDocument;
begin
  xml:=TXXMLDocument.Create(Application);
  xml.LoadFromFile('ファイルパス');
  node:=readXPath(xml, nil, 'project/name');
  xml.free;
end;

クラス拡張版

type
  TXXMLDocument=class(TXMLDocument)
  private
  public
    function readXPath(ANode: IXMLNode; AXPath: String): IXMLNode;
  end;

implementation

function TXXMLDocument.readXPath(ANode: IXMLNode; AXPath: String): IXMLNode;
var
  i,j: Integer;
  s,s2: String;
  n: IXMLNode;
begin
  j:=AnsiPos('/', AXPath);
  if (j=0) then
    begin
      j:=Length(AXPath)+1;
    end;
  s:=Copy(AXPath, 1,j-1);
  s2:=AXPath;
  Delete(s2, 1, j);
  if (ANode=nil) then
    begin
      Result:=Self.ChildNodes.FindNode(s);
    end
  else
    begin
      Result:=ANode.ChildNodes.FindNode(s);
    end;
  if (Result<>nil) and (s2<>'') then
    begin
      Result:=readXPath(Result, s2);
    end;
end;

var
  xml: TXXMLDocument;
begin
  xml:=TXXMLDocument.Create(Application);
  xml.LoadFromFile('ファイルパス');
  node:=xml.readXPath(nil, 'project/name');
  xml.free;
end;

で楽にはなりますが、遅いかも。
Comments