【发布时间】:2015-08-21 15:34:25
【问题描述】:
我从第三方网络服务器收到了一个 XML 数据包:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<SomeResponse xmlns="http://someurl">
<SomeResult>
.....
</SomeResult>
</SomeResponse>
</soap:Body>
</soap:Envelope>
为了能够跨平台,这个 XML 被加载到 Delphi 的IXMLDocument:
XmlDoc.LoadFromXML(XmlString);
我是using a solution,正在使用 XPath 查找 XML 节点。该解决方案在其他情况下有效,但是当 XML 文档包含命名空间前缀时,它会失败。
我正在尝试访问路径:
/soap:Envelope/soap:Body/SomeResponse/SomeResult
来自链接的答案:
function selectNode(xnRoot: IXmlNode; const nodePath: WideString): IXmlNode;
var
intfSelect : IDomNodeSelect;
dnResult : IDomNode;
intfDocAccess : IXmlDocumentAccess;
doc: TXmlDocument;
begin
Result := nil;
if not Assigned(xnRoot) or not Supports(xnRoot.DOMNode, IDomNodeSelect, intfSelect) then
Exit;
dnResult := intfSelect.selectNode(nodePath);
if Assigned(dnResult) then
begin
if Supports(xnRoot.OwnerDocument, IXmlDocumentAccess, intfDocAccess) then
doc := intfDocAccess.DocumentObject
else
doc := nil;
Result := TXmlNode.Create(dnResult, nil, doc);
end;
end;
它在dnResult := intfSelect.selectNode(nodePath); 与EOleException 失败:Reference to undeclared namespace prefix: 'soap'
当节点名称有命名空间前缀时,我该如何进行这项工作?
【问题讨论】:
-
您需要以某种方式告诉 XPath 处理器文档中使用的名称空间 URL。文档中使用的名称并不重要(这很好,因为未命名 SomeResponse 节点的命名空间)。一些 XML 库具有采用名称空间映射的函数;也许这个也是。然后为
http://someurl命名空间选择一个名称(例如,foo),然后在 XPath 查询中使用相同的名称(例如,foo:SomeResponse)。您还需要包含其他命名空间的名称。 -
获取
SomeResult的最简单方法是使用//SomeResponse/SomeResult而不是使用完整路径。 XmlDoc 的SelectionNamespaces属性也可能有所帮助。看here -
@kobik:请注意,
SelectionNamespaces是特定于 msxml DOM 提供程序的,并且 OP 正在寻找 xplat 解决方案;)