1. Technology

Select Single IXMLNode / TXmlNode Using XPath In Delphi's XmlDom

Get IXMLNode Using XPath's IDomNodeSelect


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;
  intfSelect : IDomNodeSelect;
  dnResult : IDomNode;
  intfDocAccess : IXmlDocumentAccess;
  doc: TXmlDocument;
  Result := nil;
  if not Assigned(xnRoot)
    or not Supports(xnRoot.DOMNode, IDomNodeSelect, intfSelect) then

  dnResult := intfSelect.selectNode(nodePath);
  if Assigned(dnResult) then
    if Supports(xnRoot.OwnerDocument, IXmlDocumentAccess, intfDocAccess) then
      doc := intfDocAccess.DocumentObject
      doc := nil;
    Result := TXmlNode.Create(dnResult, nil, doc);
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.

Delphi tips navigator:
» Hide, Slide And Fade Away Controls
« Select XML Nodes Into IXMLNodeList Using XPath In Delphi's XmlDom

©2014 About.com. All rights reserved.