2012-10-27 34 views
2

我有一个XSL文件,它充当我的应用程序的配置文件。实际上它是一个XML文件,其中包含<xsl:Stylesheet>元素。此文件被称为Config.xsl使用PowerShell更新xml元素

 <?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

'$ testconfigfile.DocumentElement.LastChild。$ key'看起来可疑我。如果你澄清你的初衷,这将有所帮助。也许举一些它应该如何工作的例子。 – Neolisk

回答

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 
+0

谢谢先生。这有效,但它只能解决部分问题。如果我的XSL(在这种情况下是Config.xsl)包含嵌套元素,那么它不起作用。我检查了你的替代解决方案,但它不是动态的,对于每个元素我可能最终添加多个属性(例如: - Name1,Name2 ... NameN)。另外,不是在脚本中对值“Config”进行硬编码,而是提取没有扩展名的文件名并动态传递它。 $ testconfigfile.DocumentElement.LastChild。$ filenamewithoutextension。($ key.Name)= $ key.Value – Santosh

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