Inno Setup读取myApp.exe.config的XML属性值返回空问题求助
问题描述
我参考了Stack Overflow上的XML读写教程,能正常读取普通XML文件,但读取myApp.exe.config(XML格式配置文件)时遇到问题。配置文件内容如下:
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <sectionGroup name="foo" type="bar"> <section name="foo2" type="bar2" allowExeDefinition="MachineToLocalUser" requirePermission="false" /> <section name="foo3" type="bar3" allowExeDefinition="MachineToLocalUser" requirePermission="false" /> </sectionGroup> </configSections> <entityFramework> <defaultConnectionFactory type="foo, bar"> <parameters> <parameter value="v12.0" /> </parameters> </defaultConnectionFactory> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> <connectionStrings> <clear /> <add name="AppEntities" connectionString="NEED THIS VALUE" providerName="System.Data.EntityClient" /> </connectionStrings> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" /> </startup> </configuration>
我用以下代码调用LoadValueFromXML函数时,始终返回空字符串:
LoadValueFromXML( ExpandConstant('{app}\\myApp.exe.config'), '//configuration/connectionStrings/add');
或者:
LoadValueFromXML( ExpandConstant('{app}\\myApp.exe.config'), '//configuration/connectionStrings');
请问哪里操作错误?
问题原因与解决方法
核心问题
你调用的LoadValueFromXML函数大概率是读取节点的文本内容,但你指定的//configuration/connectionStrings/add和//configuration/connectionStrings都是元素节点,本身没有文本内容——你要的connectionString是元素的属性值,不是节点文本,这就是返回空的原因。
解决步骤
修改XPath表达式,直接定位到目标属性
要获取add节点的connectionString属性值,XPath需要写成://configuration/connectionStrings/add[@name='AppEntities']/@connectionString其中
[@name='AppEntities']用于精准匹配指定名称的add节点,避免同类型节点干扰。确保函数支持读取属性值
如果原LoadValueFromXML函数只处理节点文本,需要调整函数逻辑来读取属性值。以下是适配的Inno Setup Pascal Script实现:function LoadValueFromXML(const FileName, XPath: string): string; var XMLNode: Variant; XMLDocument: Variant; begin Result := ''; XMLDocument := CreateOleObject('Msxml2.DOMDocument.6.0'); try XMLDocument.async := False; XMLDocument.load(FileName); if (XMLDocument.parseError.errorCode <> 0) then begin MsgBox('XML解析错误: ' + XMLDocument.parseError.reason, mbError, MB_OK); Exit; end; XMLNode := XMLDocument.selectSingleNode(XPath); if not VarIsNull(XMLNode) then begin // 判断是否为属性节点 if XMLNode.nodeType = 2 then Result := XMLNode.text else Result := XMLNode.text; end; except MsgBox('加载XML文件出错: ' + ExceptionMessage, mbError, MB_OK); end; end;正确调用示例
使用修改后的XPath调用函数,注意字符串中的单引号需要转义(用两个单引号):LoadValueFromXML( ExpandConstant('{app}\\myApp.exe.config'), '//configuration/connectionStrings/add[@name=''AppEntities'']/@connectionString');
内容的提问来源于stack exchange,提问作者pburgr
相关产品推荐
相关产品推荐

