加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

PowerShell解析xml并保存更改

发布时间:2020-12-16 07:42:44 所属栏目:百科 来源:网络整理
导读:我正在解析csproj文件以进行nuget安装,我有一个需要修改的节点.所讨论的节点是名为“Generator”的节点,其值等于“TextTemplatingFileGenerator”,它的父节点具有“WebConfigSettingsGeneratorScript.tt”的属性(第二部分还没有在这里). 这是我已经得到的脚
我正在解析csproj文件以进行nuget安装,我有一个需要修改的节点.所讨论的节点是名为“Generator”的节点,其值等于“TextTemplatingFileGenerator”,它的父节点具有“WebConfigSettingsGeneratorScript.tt”的属性(第二部分还没有在这里).

这是我已经得到的脚本,但还没有完成.它正在工作,但它会保存一个空文件.另外,它没有我的where子句的第二部分,也就是

$path = 'C:ProjectsIntouchNuGetTestPackageNuGetTestPackage'
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="T4WebConfigSettingGeneratorScript.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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读