【问题标题】:Reading from XML based on multiple attributes基于多个属性从 XML 中读取
【发布时间】:2012-04-12 06:48:48
【问题描述】:

我有一个格式如下的 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>

在这里,使帐户独一无二的是属性IDCity 的组合。

我如何唯一地阅读Amount?如何读取 IDCity 属性组合的数量?

例如,我需要为具有ID=225City=London 的帐户获取Amount。如果我使用类似的代码

Node.GetAttribute('ID')=225

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

谢谢你。

【问题讨论】:

  • 你如何使用Node.GetAttribute('ID')=225?你是循环使用还是...?
  • 是的..我在循环中使用它。类似... Node:=rootNode.ChildNodes.FindNode('Accounts'); for i := 0 to Node.ChildNodes.Count - 1 do begin childnode:= Node.ChildNodes[i]; if Node.HasAttribute('ID') then amount:=Node.GetAttribute('ID'); …..
  • 然后你可以在你的 if 语句中添加第二个条件来比较 City 的内容。

标签: xml delphi delphi-2010


【解决方案1】:

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

【讨论】:

  • +1。您也可以使用 XPath:/Accounts/Account[@ID="%s" and @City="%s"]
【解决方案2】:
function getAmount(Id, City: string): string;
begin
  Result := ''
  aNode := xmldocument1.DocumentElement.ChildNodes['Accounts'];
  for i := 0 to ChildNodes.Count do 
    with aNode.Nodes[i] do
      if (Attributes['ID'] = Id) and (Attributes['City'] = City) then 
      begin
        Result:= Attributes['Amount'];
        Break;
      end;
  end;
end;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多