Pages

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

<ResourceSet>
    <Resources>
        <Id>ID</Id>
        <Link role="self">http://theprofessionalspoint.blogspot.com/</Link>
        <Status>Pending</Status>            
    </Resources>
</ResourceSet>

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

function TForm1.RunXPathQueryInDelphi(XMLFilename : 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"]');  //XPath Query
    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;

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.