簡體   English   中英

解析從第三方 Web 服務讀取的未知 XML

[英]Parsing an unknown XML read from a third-party webservice

我正在嘗試分析像這樣的 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;

正如@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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM