0

I am trying to remove Project/ItemGroup/Reference/Private element from csproj xml.

    $csproj = [xml] ( Get-Content $fullProjectPath )

    $csproj.Project.ItemGroup | 
        ForEach-Object { $_.Reference } | 
        where { $_.Include -match "^(Some).+"} | 
        ForEach-Object { 
            if( $_.Private -ne $null ) { 
                $_.RemoveChild($_.SelectSingleNode("Private"))                                        
            } 
        }

I am getting an error $_.SelectSingleNode("Private"). Why it can find child node Private?

Bhavesh
  • 293
  • 4
  • 10
  • @Richard. Exception calling "RemoveChild" with "1" argument(s): "Object reference not set to an instance of an object." i.e. $_.SelectSingleNode("Private") is returning a null object – Bhavesh Nov 09 '12 at 09:45

1 Answers1

2

After providing the error information to @Richard question, I realized it must be something wrong with the XPath. What could be wrong in the simple XPath? I was trying to get the immediate child node. Then tried the classic debugging technique, write output to console, output the InnerXml of the parent node. In the output I noticed the xml output had namespace. So on further search on stackoverflow found out how to resolve xml namespace.

Here is the link for resolving namespace. And the fixed script.

    $csproj = [xml] ( Get-Content $fullProjectPath )

    [System.Xml.XmlNamespaceManager] $nsmgr = $xml.NameTable;
    $nsmgr.AddNamespace('msbuild','http://schemas.microsoft.com/developer/msbuild/2003');

    $csproj.Project.ItemGroup | 
        ForEach-Object { $_.Reference } | 
        where { $_.Include -match "^(Some).+"} |  
        ForEach-Object { 
            if( $_.Private -ne $null ) { 
                $_.RemoveChild($_.SelectSingleNode("msbuild:Private", $nsmgr)) 
            }
        }  
Community
  • 1
  • 1
Bhavesh
  • 293
  • 4
  • 10
  • +1 for working through this and discovering why stating the error rather than just "it doesn't work" is important, even before asking anyone else. – Richard Nov 09 '12 at 11:00
  • Thanks. I did try to debug before posting. But I guess its difficult to think straight towards the end of the day. And then following morning you find the answer easily. – Bhavesh Nov 09 '12 at 17:29