Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting xml value in powershell failing with Property '...' cannot be found on this object

Tags:

powershell

xml

I am trying to load a csproj file and change it's root namespace in powershell.

The xml of the csproj file looks like:

<Project...xmlsns="   >
    <PropertyGroup>
        <RootNamespace>SomeNamespace</RootNamespace>

...

I can get the value, navigating by property

> $xmlDoc = (Get-Content myProject.csproj)

> $xmlDoc.Project.PropertyGroup.RootNamespace ## Outputs SomeNamespace

But i can't assign to it - Setting xml value in powershell failing with Property '...' cannot be found on this object...

I have tried it with a handcrafted xml file and succeeded

<Test>
   <TestInner1>
      <TestInner2>SomeValue</TestInner2>
   </TestInner1>
</Test>

>$xmlDoc = [xml](Get-Content test.xml)
>$xmlDoc.Test.TestInner1.TestInner2 = "Some Other Value"
>$xmlDoc.Test.TestInner1.TestInner2 ## Returns Some Other Value

I have modified the elements under TestInner2 - added additional elements, self closed elements. I've added a namespace to Test. Still able to set the value in each of these cases.

When in the powershell ISE, getting intellisense for the types I note that in my test xml each of Test, TestInner1 and TestInner2 are all XmlElements. However on the project file Project and PropertyGroup are XmlElements - but then the Intellisense stops and doesn't provide RootNamespace. When i get the type of PropertyGroup it's an Object[], and of RootNamespace is string. RootNamespace claims to have be { get; set; } but i get the aforementioned error on setting.

If there is a workaround that works on the project file I'm interested, but I'm equally interested to know why the two examples above differ i.e what am i missing !

like image 973
Disgruntled Goat Avatar asked Jun 24 '14 11:06

Disgruntled Goat


1 Answers

There is more than one PropertyGroup node under Project node. Usually.

XmlDocument class will return first element if there is only one, but if there is more it will require an index. Your Test example works because there is only one sub element with name TestInner2. If you know the position of the PropertyGroup element you can access it by index

$xmlDoc.Project.PropertyGroup[0].RootNamespace

Or you use the Force to bend xml to your will

($xmlDoc.Project.PropertyGroup | Where-Object { $_['RootNamespace'] -ne $null}).RootNamespace = "new value"
like image 85
Serjx86 Avatar answered Oct 18 '22 04:10

Serjx86