您可以使用XPath http://www.w3.org/TR/xpath/选择所有作者,使用这样的表达式//catalog/subject/book/author
,从 delphi 中,您有很多选项来管理 XML 文件,但在这种情况下,最easy是使用Microsoft XML DOM implementation http://msdn.microsoft.com/en-us/library/ms760218%28v=VS.85%29.aspx
检查这个示例应用程序
{$APPTYPE CONSOLE}
uses
ActiveX,
Variants,
ComObj,
SysUtils;
procedure ReadXMLFile(const FileName:TFileName);
const
Msxml2_DOMDocument='Msxml2.DOMDocument.6.0';
var
XmlDoc : OleVariant;
Nodes : OleVariant;
lNodes : Integer;
i : Integer;
begin
//create an instance to the XML DOM
XmlDoc := CreateOleObject(Msxml2_DOMDocument);
try
XmlDoc.Async := False;
//load the file
XmlDoc.Load(FileName);
//set the xpath mode
XmlDoc.SetProperty('SelectionLanguage','XPath');
//check for errors in the xml file
if (XmlDoc.parseError.errorCode <> 0) then
raise Exception.CreateFmt('Error in Xml Data %s',[XmlDoc.parseError]);
//select the nodes with match with the expression
Nodes := XmlDoc.selectNodes('//catalog/subject/book/author');
//get the number of nodes selected
lNodes:= Nodes.Length;
Writeln(Format('%d Authors found',[lNodes]));
//traverse the nodes
for i:=0 to Nodes.Length - 1 do
Writeln(Format('Author Name %s',[Nodes.Item(i).Text]));
finally
XmlDoc :=Unassigned;
end;
end;
begin
try
CoInitialize(nil);
try
ReadXMLFile(ExtractFilePath(ParamStr(0))+'test.xml');
finally
CoUninitialize;
end;
except
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.
最后应用程序将返回这个
12 Authors found
Author Name Gambardella, Matthew
Author Name Galos, Mike
Author Name Ralls, Kim
Author Name Corets, Eva
Author Name Corets, Eva
Author Name Corets, Eva
Author Name Randall, Cynthia
Author Name Thurman, Paula
Author Name Knorr, Stefan
Author Name Kress, Peter
Author Name O'Brien, Tim
Author Name O'Brien, Tim