xml - PowerShell 解析 xml 并保存更改

标签 xml powershell

我正在为 nuget 安装解析一个 csproj 文件,我有一个节点需要更改。有问题的节点是名为“Generator”的节点,它的值等于“TextTemplatingFileGenerator”,它的父节点有一个属性“WebConfigSettingsGeneratorScript.tt”(第二部分还没有在这里)。

这是我得到的脚本,但还没有完全完成。它正在工作,但它保存了一个空文件。此外,它没有我的 where 子句的第二部分,即

$path = 'C:\Projects\Intouch\NuGetTestPackage\NuGetTestPackage'
cd $path
$files = get-childitem -recurse -filter *.csproj
foreach ($file in $files){
    ""
    "Filename: {0}" -f $($file.Name)
    "=" * ($($file.FullName.Length) + 10)   

    if($file.Name -eq 'NuGetTestPackage1.csproj'){
        $xml = gc $file.FullName | 
        Where-Object { $_.Project.ItemGroup.None.Generator -eq 'TextTemplatingFileGenerator' } | 
        ForEach-Object { $_.Project.ItemGroup.None.Generator = '' }
        Set-Content $file.FullName $xml
    }   
}

这是 XML 的基本版本:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <None Include="T4\WebConfigSettingGeneratorScript.tt">
      <Generator>TextTemplatingFileGenerator</Generator>
      <LastGenOutput>WebConfigSettingGeneratorScript.txt</LastGenOutput>
    </None>

非常感谢。我完全是 PowerShell n00b!

最佳答案

正如@empo 所说,您需要将 gc $file.FullName 的输出转换为 [xml],例如$xml = [xml](gc $file.FullName)。然后在进行更改之后但在循环到下一个文件之前,您需要保存文件,例如$xml.Save($file.FullName)

这适用于您提供的示例项目:

$file = gi .\test.csproj
$pattern = 'TextTemplatingFileGenerator'
$xml = [xml](gc $file)
$xml | Where {$_.Project.ItemGroup.None.Generator -eq $pattern} |
       Foreach {$_.Project.ItemGroup.None.Generator = ''}
$xml.Save($file.Fullname)

关于xml - PowerShell 解析 xml 并保存更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6037761/

相关文章:

c# - XMLNode 上 SetUserData 和 GetUserData 的等价物

java - 如何更改 BottomNavigationView 中特定项目的 iconTint

python - 在python中使用lxml添加xml前缀声明

powershell - 运行 Get-ADGroupMember 时出现延迟

powershell - 如何快速检查是否可以从远程计算机提取WMI信息

Python xml 遍历问题和答案

xml - Twitter:搜索我的推文并检索用户 ID,与我的关注者交叉引用?

powershell - Nuget 包 - 将文件重命名为基于项目命名空间

powershell - 远程Powershell脚本无法安装.exe

powershell - 一个命令中的 Powershell 中的多种前景色,包括空格