delphi读取xml元素

发布于 2024-10-28 03:44:54 字数 2017 浏览 1 评论 0原文

我是 XML 新手,我们需要使用新的 Bing 空间数据 API 进行地理编码。我已经设法以 xml 格式从他们那里得到结果。我将如何阅读响应中的特定元素,即。链接、状态和错误消息?

<?xml version="1.0" encoding="utf-8"?>
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
    <Copyright>Copyright © 2011 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.</Copyright>
    <BrandLogoUri>http://spatial.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>
    <StatusCode>201</StatusCode>
    <StatusDescription>Created</StatusDescription>
    <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>
    <TraceId>ID|02.00.82.2300|</TraceId>
    <ResourceSets>
        <ResourceSet>
            <EstimatedTotal>1</EstimatedTotal>
            <Resources>
                <DataflowJob>
                    <Id>ID</Id>
                    <Link role="self">https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/ID</Link>
                    <Status>Pending</Status>
                    <CreatedDate>2011-03-30T08:03:09.3551157-07:00</CreatedDate>
                    <CompletedDate xsi:nil="true" />
                    <TotalEntityCount>0</TotalEntityCount>
                    <ProcessedEntityCount>0</ProcessedEntityCount>
                    <FailedEntityCount>0</FailedEntityCount>
                </DataflowJob>
            </Resources>
        </ResourceSet>
    </ResourceSets>
</Response>

我正在使用德尔福XE。

问候, 彼得

I'm new to XML and we need to do GeoCoding with the new Bing Spatial Data API. I've managed to get a result back from them in xml format. How would I read specific elements in the response, ie. the Link, Status and ErrorMessages?

<?xml version="1.0" encoding="utf-8"?>
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
    <Copyright>Copyright © 2011 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.</Copyright>
    <BrandLogoUri>http://spatial.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>
    <StatusCode>201</StatusCode>
    <StatusDescription>Created</StatusDescription>
    <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>
    <TraceId>ID|02.00.82.2300|</TraceId>
    <ResourceSets>
        <ResourceSet>
            <EstimatedTotal>1</EstimatedTotal>
            <Resources>
                <DataflowJob>
                    <Id>ID</Id>
                    <Link role="self">https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/ID</Link>
                    <Status>Pending</Status>
                    <CreatedDate>2011-03-30T08:03:09.3551157-07:00</CreatedDate>
                    <CompletedDate xsi:nil="true" />
                    <TotalEntityCount>0</TotalEntityCount>
                    <ProcessedEntityCount>0</ProcessedEntityCount>
                    <FailedEntityCount>0</FailedEntityCount>
                </DataflowJob>
            </Resources>
        </ResourceSet>
    </ResourceSets>
</Response>

I'm using Delphi XE.

Regards, Pieter

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

坦然微笑 2024-11-04 03:44:54

使用一些简单的 XPATH 来获取请求的值怎么样?

//Link[1]/node() - 从整个文档中选择第一个“链接”节点,然后选择任何类型的第一个子节点。恰好第一个子节点是包含实际 https 链接的未命名节点。

假设 XML 文档已加载到 Doc: TXMLDocument 中,您可以使用以下代码提取链接:

(Doc.DOMDocument as IDomNodeSelect).selectNode('//Link[1]/node()').nodeValue

您可以找到一些有关 XPath 的文档 阅读 MSDN 上的 XPath 示例。您可能会在 w3schools 找到更好的文档。最重要的是,这是一个简单(但完整)的控制台应用程序,它使用 XPath 来提取并显示 3 个请求的值:

program Project14;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Xmldoc,
  xmldom,
  ActiveX;

var X: TXMLDocument;
    Node: IDOMNode;
    Sel: IDomNodeSelect;

begin
  try
    CoInitialize(nil);

    X := TXMLDocument.Create(nil);
    try

      // Load XML from a string constant so I can include the exact XML sample from this
      // question into the code. Note the "SomeNode" node, it's required to make that XML
      // valid.

      X.LoadFromXML(
        '<SomeNode>'+
        '  <Link role="self">' +
        '    https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/jobid' +
        '  </Link>' +
        '  <Status>Aborted</Status>' +
        '  <ErrorMessage>The data uploaded in this request was not valid.</ErrorMessage>' +
        '</SomeNode>'
      );

      // Shortcut: Keep a reference to the IDomNodeSelect interface

      Sel := X.DOMDocument as IDomNodeSelect;

      // Extract and WriteLn() the values. Painfully simple!

      WriteLn(Sel.selectNode('//Link[1]/node()').nodeValue);
      WriteLn(Sel.selectNode('//Status[1]/node()').nodeValue);
      WriteLn(Sel.selectNode('//ErrorMessage[1]/node()').nodeValue);

      ReadLn;
    finally X.Free;
    end;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

How about using some simple XPATH to get the requested values?

//Link[1]/node() - selects the first "Link" node from the whole document, and then selects the first child node of any kind. It just happens that the first child node is the unnamed node containing the actual https link.

Assuming the XML document is loaded into Doc: TXMLDocument, you can extract the Link with this code:

(Doc.DOMDocument as IDomNodeSelect).selectNode('//Link[1]/node()').nodeValue

You can find some documentation about XPath reading those XPath Examples on MSDN. You might find better documentation at w3schools. And to top it all up, here's a simple (but complete) console application that uses XPath to extract and display the 3 requested values:

program Project14;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Xmldoc,
  xmldom,
  ActiveX;

var X: TXMLDocument;
    Node: IDOMNode;
    Sel: IDomNodeSelect;

begin
  try
    CoInitialize(nil);

    X := TXMLDocument.Create(nil);
    try

      // Load XML from a string constant so I can include the exact XML sample from this
      // question into the code. Note the "SomeNode" node, it's required to make that XML
      // valid.

      X.LoadFromXML(
        '<SomeNode>'+
        '  <Link role="self">' +
        '    https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/jobid' +
        '  </Link>' +
        '  <Status>Aborted</Status>' +
        '  <ErrorMessage>The data uploaded in this request was not valid.</ErrorMessage>' +
        '</SomeNode>'
      );

      // Shortcut: Keep a reference to the IDomNodeSelect interface

      Sel := X.DOMDocument as IDomNodeSelect;

      // Extract and WriteLn() the values. Painfully simple!

      WriteLn(Sel.selectNode('//Link[1]/node()').nodeValue);
      WriteLn(Sel.selectNode('//Status[1]/node()').nodeValue);
      WriteLn(Sel.selectNode('//ErrorMessage[1]/node()').nodeValue);

      ReadLn;
    finally X.Free;
    end;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
把回忆走一遍 2024-11-04 03:44:54

如果 XML 结构相当稳定,您可以使用 XML 绑定工具生成普通的 Delphi 类来访问 xml 文档。

请查看此页面

If the XML-structure is fairly stable, you could use the XML binding tool to generate ordinary Delphi classes to access the xml-document.

Take a look at this page.

你没皮卡萌 2024-11-04 03:44:54

由于这些 Bing 空间数据服务有一个 XML 架构,最简单的方法是使用 Delphi XML 数据绑定向导导入该架构,然后使用生成的 Delphi 类和接口从 XML 获取数据,或将数据放入 XML 中。

这与 Jørn E. Angeltveit 的建议类似,但是 他的建议使用纯 XML 来生成类。
如果您没有架构,那也没关系,但是当您有架构时,导入架构总是更好。

有很多关于使用 Delphi XML 数据绑定向导,所以先从那里开始。

如果您需要有关绑定的帮助:请在此处提出新的具体问题。

Since there is an XML Schema for these Bing Spatial Data Services, the easiest way to go is to import that schema using the Delphi XML Data Binding Wizard, then use the generated Delphi classes and interfaces to get your data from the XML, or put data in the XML.

This is similar to what Jørn E. Angeltveit suggested, but his suggestion uses the plain XML to generate the classes from.
That is OK if you don't have a schema, but when you have a schema, it is always better to import the schema.

Thare are many examples on using the Delphi XML Data Binding Wizard, so start there first.

If you need help on the binding: please ask a new specific question here.

一个人的旅程 2024-11-04 03:44:54

现在您应该解析 XML 文件。在最简单的情况下(您知道 XML 标签),它可能如下所示:

var
  XMLDoc: IXMLDocument;
  Node: IXMLNode;
  I: Integer;
  role, link: string;

begin
  XMLDoc:= TXMLDocument.Create(nil);
  XMLDoc.LoadFromFile(AFileName);

  for I:= 0 to XMLDoc.DocumentElement.ChildNodes.Count - 1 do begin
    Node:= XMLDoc.DocumentElement.ChildNodes[I];
    if Node.NodeType = ntElement then begin
      if Node.NodeName = 'Link' then begin
        if Node.HasAttribute('role') then
          role:= Node.Attributes['role'];
        if not VarIsNull(Node.NodeValue) then
          link:= Node.NodeValue;
[..]
      end;
    end;
  end;
end;

Now you should parse XML file. In the most simple case (you know XML tags) it could look like this:

var
  XMLDoc: IXMLDocument;
  Node: IXMLNode;
  I: Integer;
  role, link: string;

begin
  XMLDoc:= TXMLDocument.Create(nil);
  XMLDoc.LoadFromFile(AFileName);

  for I:= 0 to XMLDoc.DocumentElement.ChildNodes.Count - 1 do begin
    Node:= XMLDoc.DocumentElement.ChildNodes[I];
    if Node.NodeType = ntElement then begin
      if Node.NodeName = 'Link' then begin
        if Node.HasAttribute('role') then
          role:= Node.Attributes['role'];
        if not VarIsNull(Node.NodeValue) then
          link:= Node.NodeValue;
[..]
      end;
    end;
  end;
end;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文