Powershell Surgical XML Editing

I work with csproj files using Powershell to do large-scale editing of project links. So far, I have been able to edit the Include attributes on ProjectReferences using the following lines:

$projectXml = [xml](Get-Content $_.Project.FullName) Add-TfsPendingChange -edit $_.Project.FullName -ErrorAction Stop $projectXml | Select-Xml -namespace @{msb = "http://schemas.microsoft.com/developer/msbuild/2003"} -xpath "//msb:ProjectReference[msb:Project='$projectGuid']" | Select-Object -ExpandProperty Node | foreach { $_.Include = "$newPath" } $projectXml.Save($_.Project.FullName) 

This works and replaces the Include attribute with the corresponding ProjectReferences, as I expect. However, there are many additional β€œharmless” changes, such as formatting all tags on their own line, for example.
<FileUpgradeFlags></FileUpgradeFlags>

becomes

<FileUpgradeFlags>
</FileUpgradeFlags>

Is there a way to do an edit that does not have these side effects?

edit: for clarity, for anyone who finds this message for other reasons, Select-MsBuildXml is just a wrapper function that I wrote in Select-Xml that preloads the namespace parameter in the msbuild namespace and extends the node property after that.

+6
xml formatting powershell side-effects select-xml
source share
1 answer

A few years ago I worked a lot on the VS project. It seems that creating an XmlDocument and using Load directly (compared to using Get-Content and casting in XML) worked better for me:

 $path = "C:\temp\foo.csproj" $proj = new-object system.xml.xmldocument $proj.PreserveWhitespace = $true $proj.Load($path) ... $proj.Save($path) 

Refresh . Try setting the PreserveWhitespace property to true before loading the XML document, as shown above.

+12
source share

All Articles