gpt4 book ai didi

xml - 使用Powershell更新xml元素

转载 作者:行者123 更新时间:2023-12-02 23:15:34 24 4
gpt4 key购买 nike

我有一个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)
}

最佳答案

这应该为您工作。将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

关于xml - 使用Powershell更新xml元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13095945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com