9

I'm using powershell 2.0 to edit a lot of csproj files. One of the requirements for editing is to add new PropertyGroup with different condition (Please check the example below)

<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'My-New-Env|AnyCPU'">

The problem is that powershell added the empty xmlns for all new PropertyGroup tags that I have added.

Eg:

<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'My-New-Env|AnyCPU'" xmlns="">

Is there any way to add new xml node without having any namespace?

I tried removing the namespace attribute by using the code below before adding new PropertyGroup but it didn't work. (meaning that attribute is not actually removed and I can still see the empty namespace after adding new node.)

$content = [xml](gc $_.FullName);     

    Write-Host "Reading "$_.FullName -foregroundcolor yellow;

    $project = $content.Project;

    $content.Project.RemoveAttribute("xmlns");

Edit: I'm following this post for adding new node.

How to add new PropertyGroup to csproj from powershell

Example:

$content = [xml](gc $_.FullName); 
  $importNode = $content.ImportNode($configs.DocumentElement, $true) 
  $project = $content.Project;
  $project
  $project.AppendChild($importNode);
  # $content.Save($_.FullName);
Community
  • 1
  • 1
Michael Sync
  • 4,834
  • 10
  • 40
  • 58
  • Please add the code you are using to add the nodes. – Andy Arismendi Apr 25 '12 at 03:00
  • This is the same question: http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/39af0a88-fedd-46d5-baea-12f8b2cfdacd (and the underlying problem is: understanding XML namespaces). – Richard May 04 '12 at 10:59

2 Answers2

10

Looking at this thread: http://bytes.com/topic/net/answers/377888-importing-nodes-without-namespace, it seems that it can't be easily done, you can, however go with a workaround:

Instead of:

$content.Save($_.FullName);

Use:

$content = [xml] $content.OuterXml.Replace(" xmlns=`"`"", "")
$content.Save($_.FullName);
Jason C
  • 38,729
  • 14
  • 126
  • 182
Andrey Marchuk
  • 13,301
  • 2
  • 36
  • 52
8

csproj document has default namespace. Hence when creating the element you need to refer to the same namespace otherwise you will find the xml generated with xmlns set to empty string.

Here is the link where I found the solution

$elem = $content.CreateElement("PropertyGroup", $content.DocumentElement.NamespaceURI);
$content.Project.AppendChild($elem);
Community
  • 1
  • 1
Bhavesh
  • 293
  • 4
  • 10