【问题标题】:Extract values inside XML提取 XML 中的值
【发布时间】:2013-09-05 12:01:13
【问题描述】:

我需要解析以下 XML:

<?xml version="1.0" encoding="UTF-8" ?>
<revista numero="2226" data="03/09/2013">
  <processo numero="902987089">
    <despachos>
      <despacho codigo="IPAS139"/>
    </despachos>
    <titulares>
      <titular nome-razao-social="AAAAA" pais="BR" uf="PR"/>
    </titulares>
  </processo>
  <processo numero="902812165">
    <despachos>
      <despacho codigo="IPAS029"/>
    </despachos>
    <titulares>
      <titular nome-razao-social="XXXX" pais="BR" uf="SC"/>
    </titulares>
(...)

我完全没有使用 XML 的经验。我在德尔福使用IXMLDocument

LNodeElement := LDocument.ChildNodes.FindNode('revista');
(...)
for I := 0 to LNodeElement.ChildNodes.Count - 1 do
(...)

我的问题是如何达到&lt;processo&gt; 标签内的numero 属性值?但是,如果一个善良的灵魂可以分享一个小例子,那将不胜感激。

【问题讨论】:

    标签: xml delphi delphi-xe


    【解决方案1】:

    例如这样:

    uses
      XMLDoc, XMLIntf;
    
    procedure TForm3.Button1Click(Sender: TObject);
    var
      I: Integer;
      NumberAttr: IXMLNode;
      XMLDocument: IXMLDocument;
      ProcessNodes: IXMLNodeList;
    begin
      // load an XML file
      XMLDocument := LoadXMLDocument('c:\File.xml');
      // take the list of all "revista/processo" nodes
      ProcessNodes := XMLDocument.DocumentElement.ChildNodes;
      // and iterate that "processo" node collection
      for I := 0 to ProcessNodes.Count - 1 do
      begin
        // try to find the "numero" attribute for currently iterated "processo" node
        NumberAttr := ProcessNodes[I].AttributeNodes.FindNode('numero');
        // if the "numero" attribute was found, show its value (or do something else)
        if Assigned(NumberAttr) then
          ShowMessage(NumberAttr.Text);
      end;
    end;
    

    【讨论】:

    • 等等,这是错误的,不是吗?你会得到&lt;revista&gt;标签的值,不是吗?我正在迭代&lt;processo&gt; 标签...您错过了句子中最重要的单词我如何才能达到标签内的“numero”值,但是那里缺少哪个标签。 numero 属性在两个标签中,在 &lt;revista&gt;&lt;processo&gt; 标签中。
    • 没错。我需要 中的“numero”。第一个不需要。
    • 啊抱歉,在问题中,just hidden 因为它是一个未引用的标签。好吧,这次我很幸运:-)
    • @MiguelE:我知道您已经接受了答案,但您可以做的另一件事是编写一个 XSD 文件并使用 Delphi XML Data binder 向导生成一个实用程序单元来处理XML。编写 XSD 文件很容易,link 对此进行了很好的解释。通过这样做,您的应用程序的代码将更加简单。
    • 你需要更深一层。您正在尝试读取&lt;despachos&gt; 节点中的codigo 属性,而不是&lt;despacho&gt; 中的属性。您也可以使用FindNode 来执行此操作,如您在问题中所示(查看this example)。我在这里使用该节点列表只是因为我要迭代所有相同级别的&lt;processo&gt; 节点。
    猜你喜欢
    • 2019-08-12
    • 2013-02-15
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多