从XML数据中读取URL

时间:2012-05-17 09:14:27

标签: xml delphi delphi-2010 msxml6 txmldocument

使用Delphi 2010我想使用TXMLDocument从以下XML示例数据(我省略了我不需要的部分)中读取Location的位置,Smartcard_Location和Integrated_Location:

<?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>

数据已从网络服务器加载到TXMLDcoument中。解析此数据并将URL转换为字符串值的最简单方法是什么?

1 个答案:

答案 0 :(得分:4)

最简单的方法是使用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);

如果您想使用XPath,可以使用Select Single IXMLNode / TXmlNode Using XPath In Delphi's XmlDom文章中的此功能:

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;

这样:

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