gpt4 book ai didi

xml - Delphi Xpath XML 查询

转载 作者:数据小太阳 更新时间:2023-10-29 01:59:41 26 4
gpt4 key购买 nike

我正在尝试查找 <Link role="self"> 的值 在以下 XML 文件中使用 XPath查询:

<?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>

我在 previous post 中看到了一个 XPath 查询,但我一直收到未分配的 iNode 在下面的代码中。

function TForm1.QueryXMLData(XMLFilename, XMLQuery: string): string;
var
iNode : IDOMNode;
Sel: IDOMNodeSelect;
begin
try
XMLDoc.Active := False;
XMLDoc.FileName := XMLFilename;
XMLDoc.Active := True;

Sel := XMLDoc.DOMDocument as IDomNodeSelect;

Result := '';
iNode := Sel.selectNode('Link[@role = "self"]');
if Assigned(iNode) then
if (not VarisNull(iNode.NodeValue)) then
Result := iNode.NodeValue;

XMLDoc.Active := False;

Except on E: Exception do
begin
MessageDlg(E.ClassName + ': ' + E.Message, mtError, [mbOK], 0);
LogEvent(E.Message);
end;
end;
end;

我可以尝试如何解决这个问题?

最佳答案

如果你想在文档的任何地方找到链接,你必须在它前面加上//;像这样:

iNode := Sel.selectNode('//Link[@role = "self"][3]');

这将从文档的根开始搜索,并遍历整个文档,查找与指定条件匹配的名为 Link 的节点。

更多操作符请看这里: http://msdn.microsoft.com/en-us/library/ms256122.aspx

请注意,正如 Runner 所建议的,您还可以查询完整的 XML 路径。这将比 // 运算符更快,因为它不必盲目搜索每个节点。


编辑:为什么要请求第三个匹配节点([3] 位)? AFAICS,只有一个;如果您的真实文档确实有更多,并且您确定想要第三个,那没关系。否则,删除 [3] 查询。


此外,根据您使用的 XML 实现(供应商和版本),您可能还必须指定 XML 命名空间。在 MSXML 4 到 6 (IIRC) 中,您必须使用

XMLDoc.setProperty('SelectionNamespaces', 'xmlns:ns="http://schemas.microsoft.com/search/local/ws/rest/v1"');

这意味着在您的查询中也使用该前缀:

iNode := Sel.selectNode('//ns:Link[@role = "self"][3]');

关于xml - Delphi Xpath XML 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5511844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com