我有一个XSL文件,它充当我的应用程序的配置文件。实际上它是一个XML文件,其中包含<xsl:Stylesheet>
个元素。此文件名为Config.xsl
:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.example.org/Config">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" standalone="yes" />
<xsl:template match="/">
<Config>
<Test>somevalue</Test>
<Test1>someothervalue</Test1>
</Config>
</xsl:template>
</xsl:stylesheet>
现在我想改变一个动态传递的元素的值。
意思是,我有另一个XML文件,其中包含XPATH和值作为键名/值对。以下是XML文件Properties.xml
的内容。
<?xml version="1.0" encoding="utf-8" ?>
<ConfigFiles>
<ConfigFile>
<FileName>Config.xsl</FileName>
<Keys>
<Key Name="Config.Test" Value="newvalue" />
<Key Name="Config.Test1" Value="newvalue1" />
</Keys>
</ConfigFile>
</ConfigFiles>
以下是我的powershell代码,它不会更新元素的值。
$properties = [xml] (Get-Content Properties.xml)
$lstfiles = $properties.ConfigFiles.ConfigFile
foreach($file in $lstfiles)
{
$configfilename = $file.FileName
$filename = "C:\configs\configfilename"
$testconfigfile = [xml] (Get-Content $filename)
$lstKeys = $file.Keys.Key
foreach($key in $lstKeys)
{
#When I debug the code, I was able to assign the value using the below code (Commented). However this is not dynamic
#$testconfigfile.DocumentElement.LastChild.Config.Test = "newvalue"
#Now if I try to pass the same values dynamically by reading them from properties.xml and assigning it using the below code it does not work
$testconfigfile.DocumentElement.LastChild.$key.Name = $key.Value
}
$testconfigfile.Save($filename)
}
答案 0 :(得分:3)
这对你有用。将properties.xml更改为
<?xml version="1.0" encoding="utf-8" ?>
<ConfigFiles>
<ConfigFile>
<FileName>Config.xsl</FileName>
<Keys>
<Key Name="Test" Value="newvalue" />
<Key Name="Test1" Value="newvalue1" />
</Keys>
</ConfigFile>
</ConfigFiles>
并在shell脚本中尝试以下行,
$testconfigfile.DocumentElement.LastChild.Config.($key.Name) = $key.Value
答案 1 :(得分:1)
Alternatively...
<?xml version="1.0" encoding="utf-8" ?>
<ConfigFiles>
<ConfigFile>
<FileName>Config.xsl</FileName>
<Keys>
<Key Name1="Config" Name2='Test' Value="newvalue" />
<Key Name1="Config" Name2='Test1' Value="newvalue1" />
</Keys>
</ConfigFile>
</ConfigFiles>
$testconfigfile.DocumentElement.LastChild.($key.Name1).($key.Name2) = $key.Value