我爲我的應用程序創建了一個Inno Setup腳本,其中我試圖在後安裝步驟(主要是連接字符串)中編輯一些XML配置。我有一些非常簡單的XPath請求,但使用selectSingleNode
時出現運行時異常,而getElementsByTagName
工作正常。Inno Setup - XML編輯XPath請求不起作用
此代碼不能正常工作(NIL拋出異常的接口在運行時):
procedure ReadValueFromXML(const AFileName, APath, AAttribute, AValue: string);
var
XMLNode: Variant;
XMLDocument: Variant;
begin
XMLDocument := CreateOleObject('Msxml2.DOMDocument');
try
XMLDocument.async := False;
LOG(AFileName);
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);
LOG(XMLNode.getAttribute(AAttribute));
XMLDocument.save(AFileName);
end;
except
MsgBox('An error occured!' + #13#10 + GetExceptionMessage, mbError, MB_OK);
end;
end;
到目前爲止,我一直在試圖與幾個XPath的請求來調用它:
ReadValueFromXML(FilePath, '//Phedre', 'ConnectionString', PhedreCon.Text)
ReadValueFromXML(FilePath, '//PhedreConfiguration/Databases/Phedre', 'ConnectionString', PhedreCon.Text)
ReadValueFromXML(FilePath, '/PhedreConfiguration/Databases/Phedre', 'ConnectionString', PhedreCon.Text)
此,在另一方面,工作正常(日誌連接字符串):
procedure ReadValueFromXML(const AFileName, APath, AAttribute, AValue: string);
var
XMLNode: Variant;
XMLDocument: Variant;
Index: Integer;
begin
XMLDocument := CreateOleObject('Msxml2.DOMDocument');
try
XMLDocument.async := False;
LOG('Lecture du fichier ' + AFileName);
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.getElementsByTagName(APath);
for Index := 0 to XMLNode.length - 1 do
begin
LOG(XMLNode.item[Index].getAttribute(AAttribute));
end;
end;
except
MsgBox('An error occured!' + #13#10 + GetExceptionMessage, mbError, MB_OK);
end;
end;
使用的XML是:
<PhedreConfiguration d1p1:schemaLocation="http://ns.edf.fr/phedre/config/v1.0 ./PhedreConfiguration.xsd" xmlns:d1p1="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ns.edf.fr/phedre/config/v1.0">
<Databases>
<Phedre ConnectionString="Server=****; Port=3306; Database=****; Uid=****; Pwd=****;"/>
<Arche ConnectionString="Server=****; Port=3306; Database=****; Uid=****; Pwd=****;"/>
</Databases>
[...]
</PhedreConfiguration>
所以我的問題是:是否有任何語法我的XPath請求中有錯誤?爲什麼getElementsByTagName('Phedre')
工作和selectSingleNode('//Phedre')
不會?
當使用一個命名空間內的元素調用它,XPath表達式必須包含命名空間前綴,你需要爲了能夠註冊namepsace用它。 – choroba
你是對的!解決方法是使用'XMLDocument.setProperty('SelectionNamespaces','xmlns:ns =''http://ns.edf.fr/phedre/config/v1.0''');'並用' // ns的:Phedre'。 非常感謝! – tvarnier
@tvarnier請將它作爲答案發布。 –