xml - 使用 powershell 更新 xml 元素

标签 xml xslt powershell

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

相关文章:

.net - 打开/保存 xml,同时保留节点属性之间的换行符

c# - 使用 where 子句从父节点中删除子 XML 节点

xml - XSLT - 将值连接到现有值

xml - XSLT 忽略重复元素

powershell - 仅要求和测试命名参数

Powershell 相当于 `netsh http show sslcert ipport=' 0.0.0.0 :817 2'`

java - 让 Web 服务以 XML 形式返回数据库结果的最佳方法?

php - simplexml_load_string() 不会读取标签中带有 "soap:"的 soap 响应

xslt - 当数据结构未知时排除某些子节点

powershell - Powershell 1.0 中的异常处理