基于多个属性从XML读取

前端之家收集整理的这篇文章主要介绍了基于多个属性从XML读取前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个 XML格式如下:

<Accounts>
  <Account ID="1"   City="Bangalore" Amount="2827561.95" /> 
  <Account ID="225" City="New York"  Amount="12312.00" /> 
  <Account ID="236" City="London"    Amount="457656.00" /> 
  <Account ID="225" City="London"    Amount="23462.40" /> 
  <Account ID="236" City="Bangalore" Amount="2345345.00" /> 
</Accounts>

在这里,使帐户唯一的是属性ID和城市的组合.

如何唯一地阅读金额?如何读取ID和City属性组合的金额?

例如,我需要获取ID = 225和City = London的帐户的金额.如果我使用代码

Node.GetAttribute('ID')=225

它总是给我第一个ID = 225的节点

感谢您.

解决方法

尝试使用XPath,使用句子./Accounts/Account[@ID=\”225\”][@City=\”London“]来定位节点.

试试这个样本

{$APPTYPE CONSOLE}

uses
  MSXML,SysUtils,ActiveX,ComObj;

Const
 XmlStr =
' <Accounts>'+
'  <Account ID ="1"   City="Bangalore" Amount="2827561.95"/>'+
'  <Account ID="225" City="New York"  Amount="12312.00"/>'+
'  <Account ID="236" City="London"    Amount="457656.00"/>'+
'  <Account ID="225" City="London"    Amount="23462.40"/>'+
'  <Account ID="236" City="Bangalore" Amount="2345345.00"/>'+
'</Accounts>';

procedure Test;
Var
  XMLDOMDocument  : IXMLDOMDocument;
  XMLDOMNode      : IXMLDOMNode;
begin
  XMLDOMDocument:=CoDOMDocument.Create;
  XMLDOMDocument.loadXML(XmlStr);
  XMLDOMNode := XMLDOMDocument.selectSingleNode(Format('./Accounts/Account[@ID="%s"][@City="%s"]',['225','London']));
  if XMLDOMNode<>nil then
    Writeln(Format('Amount %s',[String(XMLDOMNode.attributes.getNamedItem('Amount').Text)]));
end;

begin
 try
    CoInitialize(nil);
    try
      Test;
    finally
      CoUninitialize;
    end;
 except
    on E:EOleException do
        Writeln(Format('EOleException %s %x',[E.Message,E.ErrorCode]));
    on E:Exception do
        Writeln(E.Classname,':',E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.

猜你在找的XML相关文章