XPath and TXmlDocument

后端 未结 1 1991
我寻月下人不归
我寻月下人不归 2020-12-03 07:58

In Delphi XE is it possible to use XPath with a TXmlDocument component?

I\'m aware I can use late binding to access the MSXML2 and then use XPath:

XM         


        
相关标签:
1条回答
  • 2020-12-03 08:04

    I can't find anything in the TXMLDocument documentation about XPath.

    XML example, from the OmniXML XPath demo:

    <?xml version="1.0" encoding="UTF-8"?>
    <bookstore>
      <book>
        <title lang="eng">Harry Potter</title>
      </book>
      <book>
        <title lang="eng">Learning XML</title>
      </book>
      <book>
        <title lang="slo">Z OmniXML v lepso prihodnost</title>
        <year>2006</year>
      </book>
      <book>
        <title>Kwe sona standwa sam</title>
      </book>
    </bookstore>
    

    Try something like this:

    uses 
      XMLDoc, XMLDom, XMLIntf;
    
    // From a post in Embarcadero's Delphi XML forum.
    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;
    
    
    var
      IDoc: IXMLDocument;
      INode: IXMLNode;
    begin
      IDoc := LoadXMLDocument('.\books.xml');
      INode := SelectNode(IDoc.DocumentElement,'/bookstore/book[2]/title'); 
    end;
    

    Just as an FYI for others, I'll leave this in: OmniXML supports XPath, and has a demo that shows really well how to use it. It's also free, comes with source, supports Unicode, and has pretty good support through it's forums.

    0 讨论(0)
提交回复
热议问题