如何读取和写入XML文档节点值?
我想读取XML文件的一些节点并在一些自定义输入字段中显示它们的值。 用户可以根据需要更改这些值,然后单击Next
按钮将这些值保存回XML。
如何在InnoSetup脚本中执行此操作?
使用CreateOleObject
函数来实例化标准的MSXML2.DOMDocument
COM对象。 以下脚本显示了如何从下面发布的XML文件中加载和保存单个节点的文本值(该脚本本身受MSDN示例的启发):
[Setup]
AppName=My Program
AppVersion=1.5
DefaultDirName={pf}My Program
DefaultGroupName=My Program
UninstallDisplayIcon={app}MyProg.exe
Compression=lzma2
SolidCompression=yes
OutputDir=userdocs:Inno Setup Examples Output
[Files]
Source: "MyProg.exe"; DestDir: "{app}"
Source: "MyProg.chm"; DestDir: "{app}"
[Icons]
Name: "{group}My Program"; Filename: "{app}MyProg.exe"
[Code]
var
CustomEdit: TEdit;
CustomPageID: Integer;
function LoadValueFromXML(const AFileName, APath: string): string;
var
XMLNode: Variant;
XMLDocument: Variant;
begin
Result := '';
XMLDocument := CreateOleObject('Msxml2.DOMDocument.6.0');
try
XMLDocument.async := False;
XMLDocument.load(AFileName);
if (XMLDocument.parseError.errorCode <> 0) then
MsgBox('The XML file could not be parsed. ' +
XMLDocument.parseError.reason, mbError, MB_OK)
else
begin
XMLDocument.setProperty('SelectionLanguage', 'XPath');
XMLNode := XMLDocument.selectSingleNode(APath);
Result := XMLNode.text;
end;
except
MsgBox('An error occured!' + #13#10 + GetExceptionMessage, mbError, MB_OK);
end;
end;
procedure SaveValueToXML(const AFileName, APath, AValue: string);
var
XMLNode: Variant;
XMLDocument: Variant;
begin
XMLDocument := CreateOleObject('Msxml2.DOMDocument.6.0');
try
XMLDocument.async := False;
XMLDocument.load(AFileName);
if (XMLDocument.parseError.errorCode <> 0) then
MsgBox('The XML file could not be parsed. ' +
XMLDocument.parseError.reason, mbError, MB_OK)
else
begin
XMLDocument.setProperty('SelectionLanguage', 'XPath');
XMLNode := XMLDocument.selectSingleNode(APath);
XMLNode.text := AValue;
XMLDocument.save(AFileName);
end;
except
MsgBox('An error occured!' + #13#10 + GetExceptionMessage, mbError, MB_OK);
end;
end;
procedure InitializeWizard;
var
CustomPage: TWizardPage;
begin
CustomPage := CreateCustomPage(wpWelcome, 'Custom Page',
'Enter the new value that will be saved into the XML file');
CustomPageID := CustomPage.ID;
CustomEdit := TEdit.Create(WizardForm);
CustomEdit.Parent := CustomPage.Surface;
end;
procedure CurPageChanged(CurPageID: Integer);
begin
if CurPageID = CustomPageID then
CustomEdit.Text := LoadValueFromXML('C:Setup.xml', '//Setup/FirstNode');
end;
function NextButtonClick(CurPageID: Integer): Boolean;
begin
Result := True;
if CurPageID = CustomPageID then
SaveValueToXML('C:Setup.xml', '//Setup/FirstNode', CustomEdit.Text);
end;
这是脚本中使用的XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<Setup>
<FirstNode>First node value!</FirstNode>
<SecondNode>Second node value!</SecondNode>
</Setup>
链接地址: http://www.djcxy.com/p/29833.html