我将假设,一旦您找到Designation
,您还想阅读与该名称相关的其他条目(Inner
、Outer
、Spin
和Cage
)。
XPath
是这个问题的完美解决方案。我的示例使用了一个新表单,其中仅包含 aTMemo
并在其上放置,并为事件TButton
添加了一个处理程序:Button1.OnClick
uses
MSXML, ComObj, ActiveX;
const
XMLText = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<Data>' +
'<Row>' +
'<Designation>1234102</Designation>' +
'<Inner>5.412</Inner>' +
'<Outer>3.588</Outer>' +
'<Spin>4.732</Spin>' +
'<Cage>0.399</Cage>' +
'</Row>' +
'<Row>' +
'<Designation>1342153</Designation>' +
'<Inner>5.916</Inner>' +
'<Outer>4.084</Outer>' +
'<Spin>5.277</Spin>' +
'<Cage>0.408</Cage>' +
'</Row>' +
'</Data>';
procedure TForm1.Button1Click(Sender: TObject);
var
XMLDoc: IXMLDOMDocument;
Node, SibNode: IXMLDOMNode;
begin
Memo1.Clear;
XMLDoc := CoDOMDocument.Create;
XMLDoc.loadXML(XMLText);
// Select the node with the Designation you want.
Node := XMLDoc.selectSingleNode('//Designation[text()="1342153"]');
if Assigned(Node) then
begin
Memo1.Lines.Add('Found it.');
Memo1.Lines.Add(Node.nodeName + ' = ' + Node.firstChild.nodeValue);
// Read all the nodes at the same level as the Designation
SibNode := Node.nextSibling;
while SibNode <> nil do
begin
Memo1.Lines.Add(SibNode.nodeName + ' = ' +
SibNode.firstChild.nodeValue);
Sib := Sib.nextSibling;
end;
end;
end;
如果您只想获取所有<Row>
元素,并遍历它们包含的信息,则可以使用它(在上面的测试应用程序中添加第二个按钮,并将其用于Button2.OnClick
处理程序):
procedure TForm1.Button2Click(Sender: TObject);
var
XMLDoc: IXMLDOMDocument;
NodeList: IXMLDOMNodeList;
Node, SibNode: IXMLDOMNode;
i: Integer;
begin
Memo1.Clear;
XMLDoc := CoDOMDocument.Create;
XMLDoc.loadXML(XMLText);
NodeList := XMLDoc.selectNodes('/Data/Row');
if Assigned(NodeList) then
begin
for i := 0 to NodeList.length - 1 do
begin
Node := NodeList.item[i];
SibNode := Node.firstChild;
while Assigned(SibNode) do
begin
Memo1.Lines.Add(SibNode.nodeName + ' = ' +
SibNode.firstChild.nodeValue);
SibNode := SibNode.nextSibling;
end;
end;
// Add a blank line between groupings for readability
Memo1.Lines.Add('');
end;
end;