在powershell中迭代XML和更新的更好方法?

时间:2022-09-23 07:37:59

I got this to work, but I am not happy with the result, and I am wondering how this can be done better.

我让这个工作,但我对结果不满意,我想知道如何做得更好。

XML

<?xml version="1.0" encoding="UTF-8"?>
<configuration version="3">
  <library>
    <default-theme>None</default-theme> 
    <export-path>Default</export-path>
    <caching-enabled>True</caching-enabled>
  </library>
</configuration>

PS

Function ModifyConfigFile()
{
  $xml = New-Object -TypeName XML
  $xml.Load($FilePath)
  $item = $xml.configuration.library 
  $item.ChildNodes.Item(1)."#text" = "Modify-Test"
  $xml.Save($NewFilePath)
}

I was trying to update the "export-path" text node, which this code does do, but the code is dependent on me knowing that this node is the 2nd item in the Child node of its parent library.

我试图更新“导出路径”文本节点,这个代码确实做了,但代码依赖于我知道这个节点是其父库的子节点中的第二个项目。

Is there a cleaner way?

有更干净的方式吗?

Or at the very least a way for me to verify that I am updating the node that I want "export-path"?

或者至少一种方式让我验证我正在更新我想要“导出路径”的节点?

1 个解决方案

#1


0  

Here's a more 'powershell' approach to loading the file, and incorporating PetSerAl comment

这是一个更加'powershell'的方法来加载文件,并结合PetSerAl评论

[xml]$doc = gc $filePath
$doc.configuration.library.'export-path' = "Modify-Test"
$doc.Save($filePath)

#1


0  

Here's a more 'powershell' approach to loading the file, and incorporating PetSerAl comment

这是一个更加'powershell'的方法来加载文件,并结合PetSerAl评论

[xml]$doc = gc $filePath
$doc.configuration.library.'export-path' = "Modify-Test"
$doc.Save($filePath)

相关文章