How do I use Powershell to add/remove references to a csproj?

后端 未结 2 655
清歌不尽
清歌不尽 2020-12-06 01:53

In relation to this previous question I am trying to create a batch file which as part must remove and add a reference to an XML *.csproj file. I have looked

2条回答
  •  情深已故
    2020-12-06 02:21

    I think the problem is that your XML file has a default namespace xmlns="http://schemas.microsoft.com/developer/msbuild/2003". This causes problems with XPath. So you XPath //ProjectReference will return 0 nodes. There are two ways to solve this:

    1. Use a namespace manager.
    2. Use namespace agnostic XPath.

    Here's is how you could use a namespace manager:

    $nsmgr = New-Object System.Xml.XmlNamespaceManager -ArgumentList $proj.NameTable
    $nsmgr.AddNamespace('a','http://schemas.microsoft.com/developer/msbuild/2003')
    $nodes = $proj.SelectNodes('//a:ProjectReference', $nsmgr)
    

    Or:

    Select-Xml '//a:ProjectReference' -Namespace $nsmgr
    

    Here's how to do it using namespace agnostic XPath:

    $nodes = $proj.SelectNodes('//*[local-name()="ProjectReference"]')
    

    Or:

    $nodes = Select-Xml '//*[local-name()="ProjectReference"]'
    

    The second approach can be dangerous because if there were more than one namespace it could select the wrong nodes but not it your case.

提交回复
热议问题