Mega Code Archive

 
Categories / Delphi / XML
 

Select Single IXMLNode TXmlNode Using XPath In Delphis XmlDom

Title: Select Single IXMLNode / TXmlNode Using XPath In Delphi's XmlDom Previous tip, XPath To Select XML Nodes , provided an XPath wrapper to select a collection of IXMLNodes using their name. The XPath's selectNodes (xmldox.pas IDomNodeSelect.selectNodes) function selects a list of nodes matching the XPath expression. To select the first node that matches the XPath expression you can use the selectNode function of the IDomNodeSelect defined in XmlDom.pas. Here's how to get the IXMLNode (TXMLNode) by wrapping the call to XPath's selectNode: class function TXMLNodeHelper.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; Note: the above is a class function. Note: a full examination of XPath and its usage is, of course, beyond the scope of this article.