在NuGet初始化脚本不工作时保存XML文档
问题描述:
我正在尝试编写一个NuGet程序包init.ps1脚本,它将修改.targets文件(XML)的一个值并保存文档。脚本没有错误地成功完成所有事情,但是当我检查文档时,它并没有被更改。在NuGet初始化脚本不工作时保存XML文档
下面是脚本:
Param($installPath, $toolsPath, $package)
$proj = Get-Project
$pack = $package
# Detect if the project installing the NuGet package is a web application and
# alters an xml element value in the .targets value to prevent duplication
# of application resources when published.
if ($proj.ExtenderNames -contains "WebApplication") {
# Begin to build neccessary path strings to find the .targets file.
# The targets file is currently located in
# \packages\packageName.packageVersion\build\packageName.targets.
$packageName = [string]$pack.Id
$packageRootDir = $installPath
# packageName.Version\build
$packageBuildFolderPath = Join-Path $packageRootDir "build"
# packageName.Version\build\packageName
$targetsFilePath = Join-Path $packageBuildFolderPath ($packageName + ".targets")
"$targetsFilePath"
if (Test-Path $targetsFilePath) {
# If the targets file path has correctly located the file then
# we edit the targets file to alter the CopyToOutputDirectory element.
# Load the targets file as an xml object
$xml = New-Object System.Xml.XmlDocument
$xml.Load($targetsFilePath)
"xml loaded"
# Search each ItemGroup element for the one containing a Content element.
foreach ($group in $xml.Project.ItemGroup) {
$nodeExists = $group.Content.CopyToOutputDirectory
if ($nodeExists) {
"$nodeExists"
# Edits the value when we find the correct node
$nodeExists = "Never"
"$nodeExists"
}
}
"xml modified"
# Save the updated document to the correct place.
$savePath = [string]$targetsFilePath
"$savePath"
$xml.Save($savePath)
"xml Saved to $savePath"
}
}
,这里是从一开始就包管理器输出,结束脚本块:
Executing script file 'path to tools/Init.ps1' 'correct path to package/build/package.targets' xml loaded Always Never xml modified 'correct path to package/build/package.targets' xml Saved to 'correct path to package/build/package.targets'
答
你的代码修改变量$nodeExists
的价值,但不包括值来自的XML节点。您可以验证通过在循环后考虑看看实际的XML数据:
$xml.Save([Console]::Out)
实际修改节点的值更改您的代码是这样的:
foreach ($group in $xml.Project.ItemGroup) {
if ($group.Content.CopyToOutputDirectory) {
$group.Content.CopyToOutputDirectory = 'Never'
}
}
或类似这样的:
$xml.SelectNodes('//Content/CopyToOutputDirectory') | ForEach-Object {
$_.'#text' = 'Never'
}
注意,后者需要namespace manager,如果你的XML使用命名空间。
+0
谢谢你的回复,这确实是一个问题。我遇到的另一个问题是在VS 2012中init.ps1脚本将被调用,然后复制.targets文件以覆盖它。但这不在这个问题的范围之内。 – BHigzz
除了实际的问题:你想在文件中修改什么? /为什么需要? –