【问题标题】:XPATH issue in C# and PowerShellC# 和 PowerShell 中的 XPATH 问题
【发布时间】:2010-11-12 23:35:24
【问题描述】:

我有以下 XML 文件,我想打印出 baseAddress 值,然后更改该值并将更新写入同一个 XML 文件。

我的问题是我在 PowerShell 中使用以下脚本进行操作,并且似乎无法检索相关值。我认为原因可能是有一个标志'。在元素名称“system.serviceModel”中,PowerShell 认为我想检索系统下的 serviceModel 子元素?任何想法如何检索 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>

提前致谢, 乔治

【问题讨论】:

  • 嗨,George,什么版本的 PowerShell?

标签: c# .net xml powershell xpath


【解决方案1】:

如果您用“.”将元素名称放在引号中你可以得到它。

使用

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

【讨论】:

  • 谢谢安迪,我找到了解决方案,$FooConfig.configuration."system.serviceModel".services.service.host.baseAddresses.add.baseaddress
【解决方案2】:

在某些情况下,只使用 XPATH 和 XML API 会更容易,例如:

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

对比:

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

【讨论】:

    猜你喜欢
    • 2013-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多