且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 PowerShell 更新 XML 节点的值?

更新时间:2023-11-24 14:06:58

我不知道你到底想达到什么目的,但这个例子应该给你和想法:

I don't know what exactly you want to achieve, but the example should give you and idea:

$file = 'c:\temp\aa\ServerService.exe.config'
$x = [xml] (Get-Content $file)
Select-Xml -xml $x  -XPath //root/level |
    % { $_.Node.'#text' = 'test'
        $_.Node.SomeAttribute = 'value'
      }
$x.Save($file)

您不需要将 .NET 用于 xpath 查询.继续使用 PowerShell(使用 Select-Xml).
通过 Get-Content 加载 xml 文件并将其转换为 [xml] 以创建 XmlDocument 并加载文件内容也很常见.

You don't need to use .NET for xpath queries. Just stay with PowerShell (with Select-Xml).
It is also common to load xml file via Get-Content and cast it to [xml] which creates XmlDocument and loads the file content.