George2
George2

Reputation: 45821

XPATH issue in C# and PowerShell

I have the following XML file and I want to print out the baseAddress value, then change the value and write update to the same XML file.

My problem is I am using the following scripts in PowerShell to manipulate, and seems the related value could not be retrieved. I think the reason may be there is a sign '.' in the element name "system.serviceModel", which PowerShell thinks I want to retrieve serviceModel sub-element under system? Any ideas how to retrieve the correct value for baseAddress?

$FooConfig = [xml](get-content .\Foo.exe.config -ErrorAction:stop)
FooConfig.configuration.system.serviceModel.services.service.host.baseAddress

<configuration>
  <system.serviceModel>
    <services>
      <service name="FooImpl" behaviorConfiguration="mexServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:9090/Foo" />
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>
</configuration>

thanks in advance, George

Upvotes: 0

Views: 566

Answers (2)

Keith Hill
Keith Hill

Reputation:

In some cases, it is easier to just use XPATH and the XML API e.g.:

PS> $FooConfig.SelectSingleNode('//add[@baseAddress]').baseAddress = 'foo'
PS> $FooConfig.SelectSingleNode('//add[@baseAddress]').baseAddress
foo

versus:

PS> $xml.configuration.'system.serviceModel'.services.service.host.baseaddresses.add.baseaddress = 'foo'
PS> $xml.configuration.'system.serviceModel'.services.service.host.baseaddresses.add.baseaddress
foo

Upvotes: 1

Andy Schneider
Andy Schneider

Reputation: 8684

If you put quotes around the element name with a "." you can get it.

use

$FooConfig.configuration."system.serviceModel".services.service.host.baseAddress

Upvotes: 3

Related Questions