2

我在 Clarius的 Daniel Cazzulino 的博客上看到了一个很好的例子。我想做一些类似他所做的事情。

我正在尝试通过NuGet提供一些基本的T4 模板并遇到问题,因为它们每个在csproj文件中都有一个条目,说明这使得它们都独立运行,这是不可取的。如果值这样读取,那么一切都会好起来的。<Generator>TextTemplatingFileGenerator</Generator><Generator></Generator>

我想使用msbuild删除此设置,就像您在上面的示例中修改csproj一样。我编写了一个PowerShell脚本来删除有问题的值,但它需要卸载项目。Msbuild似乎更适合这项任务,但我不熟悉它。我做了一些搜索,但仍然在黑暗中。

他所做的和我想做的区别在于他添加了一些东西,我想编辑一些东西,但我不知道如何使用msbuild xml 遍历方法来定位信息。

这是我在@Keith Hill 的帮助下编写的PowerShell脚本:

$ns = @{msb = 'http://schemas.microsoft.com/developer/msbuild/2003'}
$results = 0
$xml = [xml](gc $projName)
$xml | Select-Xml "//msb:Generator" -Namespace $ns | 
       Foreach { 
           $_.Node.set_InnerText('')
           $results = 1
       }
if($results -eq 1){
    $xml.Save($project.FullName)
}

有关如何在 msbuild 中执行此操作的任何建议?

这是 Daniel 的代码(它存在于作为 NuGet 安装生命周期一部分的 Install.ps1 文件中):

param($installPath, $toolsPath, $package, $project)
    # This is the MSBuild targets file to add
    $targetsFile = [System.IO.Path]::Combine($toolsPath, 'Funq.Build.targets')

    # Need to load MSBuild assembly if it's not loaded yet.
    Add-Type -AssemblyName 'Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
    # Grab the loaded MSBuild project for the project
    $msbuild = [Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($project.FullName) | Select-Object -First 1

    # Make the path to the targets file relative.
    $projectUri = new-object Uri('file://' + $project.FullName)
    $targetUri = new-object Uri('file://' + $targetsFile)
    $relativePath = $projectUri.MakeRelativeUri($targetUri).ToString().Replace([System.IO.Path]::AltDirectorySeparatorChar, [System.IO.Path]::DirectorySeparatorChar)

    # Add the import and save the project
    $msbuild.Xml.AddImport($relativePath) | out-null
    $project.Save()
4

1 回答 1

1

您可以使用XmlPoke Task执行此操作:

<Project DefaultTargets="PokeGenerator">
    <ItemGroup>
        <MyProjectFile Include="$(MSBuildProjectDirectory)\MyProject.csproj" />
    </ItemGroup>

    <Target Name="PokeGenerator">
        <XmlPoke XmlInputPath="%(ProjectConfigFile.FullPath)"
            Query="/x:Project/x:ItemGroup/x:Compile/x:Generator"
            Namespaces="&lt;Namespace Prefix='x' Uri='http://schemas.microsoft.com/developer/msbuild/2003' /&gt;"
            Value="%0a" />
    </Target>
</Project>

您只需要修改XmlInputPathQuery参数以满足您的需要。

问题是你必须声明一个命名空间前缀,即使项目文件不使用任何命名空间前缀,并且你需要提供一个值来插入选定的元素——我认为换行不会受到伤害。

于 2011-05-23T18:29:14.467 回答