2012-06-28 14 views
11

Quiero leer algunos nodos de un archivo XML y mostrar sus valores en algunos campos de entrada personalizados. El usuario puede cambiar los valores si es necesario y al hacer clic en el botón Next estos valores deben guardarse de nuevo en el XML.Cómo leer y escribir valores de nodo de documento XML?

¿Cómo hacer esto en la secuencia de comandos InnoSetup?

+0

Pregunta relacionada: [Inno Setup modify XML file based on custom input] (http://stackoverflow.com/q/8141886/588306). – Deanna

Respuesta

23

Utilice la función CreateOleObject para crear una instancia del objeto COM estándar MSXML2.DOMDocument. La siguiente secuencia de comandos muestra cómo cargar y guardar un valor de texto para un único nodo del archivo XML publicado a continuación (el propio guión se inspiró en los ejemplos de 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; 

Aquí está el archivo XML que se utiliza en el secuencia de comandos:

<?xml version="1.0" encoding="UTF-8"?> 
<Setup> 
    <FirstNode>First node value!</FirstNode> 
    <SecondNode>Second node value!</SecondNode> 
</Setup> 
+0

P.S. Sería bueno envolver cada llamada a la función de objeto OLE en este script con el ['OleCheck'] (http://www.jrsoftware.org/ishelp/topic_isxfunc_olecheck.htm) que levantará la excepción (antes) cuando la función llame falla (cuando el resultado será diferente del valor 'S_OK'). – TLama

+0

Consulte también el ejemplo [CodeAutomation.iss] (https://woofy.googlecode.com/hg/tools/Inno%20Setup/Examples/CodeAutomation.iss). – Deanna

+0

@ Deanna, estaba buscando ese ejemplo antes de publicar esto, pero se trata de cómo agregar un nodo a un archivo XML, mientras que se trata de cómo cargar y guardar el valor del nodo existente ;-) – TLama

Cuestiones relacionadas