Search code examples
xmldelphidelphi-2010msxml6txmldocument

Read URL from XML data


Using Delphi 2010 I want to read the URL's for Location, Smartcard_Location and Integrated_Location from the following XML sample data (I left out parts I don't need) using TXMLDocument:

<?xml version="1.0" encoding="UTF-8"?>
<PNAgent_Configuration xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance">
    <Request>
        <Enumeration>
            <Location replaceServerLocation="true" modifiable="true" forcedefault="false" RedirectNow="false">http://2003xa/Citrix/PNAgent/enum.aspx</Location>
            <Smartcard_Location replaceServerLocation="true">https://2003xa/Citrix/PNAgent/smartcard_enum.aspx</Smartcard_Location>
            <Integrated_Location replaceServerLocation="true">http://2003xa/Citrix/PNAgent/integrated_enum.aspx</Integrated_Location>
            <Refresh>
                <OnApplicationStart modifiable="false" forcedefault="true">true</OnApplicationStart>
                <OnResourceRequest modifiable="false" forcedefault="true">false</OnResourceRequest>
                <Poll modifiable="false" forcedefault="true">
                    <Enabled>true</Enabled>
                    <Period>6</Period>
                </Poll>
            </Refresh>
        </Enumeration>
    </Request>
</PNAgent_Configuration>

The data is already loaded from a webserver into a TXMLDcoument. What is the easiest way to parse this data and get the URL's into string values?


Solution

  • The simplest way is to use getElementsByTagName:

    lx1.Items.Add(XMLDocument1.DOMDocument.getElementsByTagName('Location').item[0].firstChild.nodeValue);
    lx1.Items.Add(XMLDocument1.DOMDocument.getElementsByTagName('Smartcard_Location').item[0].firstChild.nodeValue);
    lx1.Items.Add(XMLDocument1.DOMDocument.getElementsByTagName('Integrated_Location').item[0].firstChild.nodeValue);
    

    If you would like to use XPath instead, you can use this function from Select Single IXMLNode / TXmlNode Using XPath In Delphi's XmlDom article:

    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;
    

    This way:

    lx1.Items.Add(TXMLNodeHelper.SelectNode(XMLDocument1.DocumentElement, '//Location').NodeValue);