Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from XML based on multiple attributes

I have an XML in the following format:

<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>

Here, what makes an account unique is the combination of attributes ID and City.

How do I read the Amount uniquely? How do I read amount for a combination of ID and City attributes?

For example, I need to get the Amount for the account with ID=225 and City=London. If I use code like

Node.GetAttribute('ID')=225

it always gives me the first node with ID=225

Thanking you.

like image 929
Pradeep Avatar asked Dec 17 '22 01:12

Pradeep


1 Answers

Try with XPath, using this sentence ./Accounts/Account[@ID="225"][@City="London"] to locate the node.

Try this sample

{$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.
like image 87
RRUZ Avatar answered Dec 28 '22 08:12

RRUZ