PowerShell 解析 xml 并保存更改 [英] PowerShell parse xml and save changes

查看:46
本文介绍了PowerShell 解析 xml 并保存更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm parsing a csproj file for a nuget install and I've got a node that needs to be altered. The node in question is the node named "Generator" where it's value equals "TextTemplatingFileGenerator" and it's parent node has an attribute of "WebConfigSettingsGeneratorScript.tt" (the second part isn't in here yet).

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

Here's the script that I've got, but it's not quite done. It's working, but it saves an empty file. Also, it doesn't have the 2nd part of my where clause, which is

$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 的基本版本:

Here's a basic version of the 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!

Thanks a lot. I'm a total PowerShell n00b!

推荐答案

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

As @empo says, you need to cast the output of gc $file.FullName to [xml] e.g. $xml = [xml](gc $file.FullName). And then after making the change but before looping to the next file, you need to save the file e.g. $xml.Save($file.FullName).

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

This works with the sample project you provided:

$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)

这篇关于PowerShell 解析 xml 并保存更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆