Machine Learning Quiz (134 Objective Questions) Start ML Quiz

Deep Learning Quiz (152 Objective Questions) Start DL Quiz

Monday, 16 December 2013

How to run XPath Query in Delphi using MSXML DOM?

How to run XPath Query in Delphi using MSXML DOM?

This article illustrates a simple example on how to run XPath query to XML file in Delphi by using MSXML DOM. XPath Query is used to select a certain subset of the XML. XPath, the XML Path Language, is a query language for selecting nodes from an XML document. In addition, XPath may be used to compute values from the content of an XML document. XPath was defined by the World Wide Web Consortium. We will try to locate the value for <Link role="self"> in the following XML File using a XPath query. 

Sample XML file

        <Link role="self"></Link>

Following is a simple Delphi function to located the value in the node "Link" under attribute "role".

function TForm1.RunXPathQueryInDelphi(XMLFilename : string): string;
  iNode : IDOMNode;
  Sel: IDOMNodeSelect;
    XMLDoc.Active := False;
    XMLDoc.FileName := XMLFilename;
    XMLDoc.Active := True;

    Sel := XMLDoc.DOMDocument as IDomNodeSelect;

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

    XMLDoc.Active := False;

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

No comments:

Post a Comment