解析从第三方Web服务读取的未知XML

问题描述 投票:1回答:1

[我正在尝试分析这样的XML值(从第三方Web服务获得),将这些值插入tStringlist中以供以后检查]

<?xml version="1.0" encoding="utf-8"?>
<libretti pagina="1" n_pagine="1" n_libretti="2">
    <libretto cod_catasto="202000000011" 
              cod_chiave="5e9f2bf12" completo="si" 
              data="2020-04-21" resp_cognome="Colombo" 
              resp_nome="Gianluca" ub_comune="VILLAFRANCA DI VERONA" 
              ub_provincia="VR" ub_indirizzo="Via dei pini" 
              ub_civico="1" ub_palazzo="" ub_scala="" ub_interno=""/>
    <libretto cod_catasto="202000000012" 
              cod_chiave="5e9f2bfsw" completo="si" 
              data="2020-04-22" resp_cognome="Palumso" 
              resp_nome="Federico" ub_comune="VILLAFRANCA DI VERONA" 
              ub_provincia="VR" ub_indirizzo="Via Prosetta" 
              ub_civico="2" ub_palazzo="" ub_scala="" ub_interno=""/>
</libretti>

我真正需要的是像下面那样简单地列出所有迷信的清单。

例如:

libretto:
cod_catasto="202000000011"
cod_chiave="5e9f2bf12"
ompleto="si"
data="2020-04-21"
resp_cognome="Colombo"
resp_nome="Gianluca" 
ub_comune="VILLAFRANCA DI VERONA" 
ub_provincia="VR" 
ub_indirizzo="Via dei pini" 
ub_civico="1" 
ub_palazzo="" 
ub_scala="" 
ub_interno=""

依此类推...

我被下面的代码所困,它不会列出所有值,但会停在第一个值,仅显示值“ libretto =”

procedure TForm5.ParseCercaXMLToMemo(TestXML:String);
var
  Doc: IXMLDocument;
  i: Integer;
  LDocument: IXMLDocument;
  LNodeElement, LNode: IXMLNode;
  LAttrValue: string;

begin
  LDocument := TXMLDocument.Create(nil);
  LDocument.LoadFromXML(TestXML); 

  { Find a specific node. }
  LNodeElement := LDocument.ChildNodes.FindNode('libretti');

  if (LNodeElement <> nil) then
  begin
    for I := 0 to LNodeElement.ChildNodes.Count - 1 do
    begin
      LNode := LNodeElement.ChildNodes.Get(I);
      memo1.lines.add(LNode.NodeName + '=' + LNode.Text);
    end;
  end;

end;
delphi xml-parsing
1个回答
1
投票

根据@Oliver的建议,我尝试了此代码,该代码最终按预期方式工作。

procedure TForm5.ParseCercaXMLToMemo(TestXML:String);
var
  Doc: IXMLDocument;
  i,y: Integer;
  LDocument: IXMLDocument;
  LNodeElement, LNode: IXMLNode;
  LAttrValue: string;

begin
  LDocument := TXMLDocument.Create(nil);
  LDocument.LoadFromXML(TestXML); { File should exist. }

  { Find a specific node. }
  LNodeElement := LDocument.ChildNodes.FindNode('libretti');
  if (LNodeElement <> nil) then
  begin
    for I := 0 to LNodeElement.ChildNodes.Count - 1 do
    begin
      for y := 0 to LNodeElement.ChildNodes[i].AttributeNodes.count-1 do
        begin
          memo1.lines.add(LNodeElement.ChildNodes[i].AttributeNodes[y].LocalName+' = '+LNodeElement.ChildNodes[i].AttributeNodes[y].Text);
        end;
    end;
  end;

end;
© www.soinside.com 2019 - 2024. All rights reserved.