无法使用Powershell从xml标记中获取值

时间:2014-06-05 21:33:07

标签: xml powershell xml-parsing powershell-v2.0

我有一个像这样的xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<settings>
    <serviceUrlFiles>
        <file>Licensed/Mobile/android/Phone/res/xml/preferences.xml</file>
        <file>Licensed/Mobile/iOS/FIService/Resources/Settings.bundle/Root.plist</file>
        <file>Licensed/Mobile/javascript/src/shared/config/settings.json</file>
            <file>Framework/Mobile/iOS/FIToolkit/FIToolkit/NativeSOAPService/MCProcessSOAPRequest.m</file>
    </serviceUrlFiles>
    <builds>
        <build type="internal.qa">
            <serviceUrl regexp="[a-zA-Z0-9_\-\.]*://[a-zA-Z0-9_\.-]*/RichChannel[0-9a-zA-Z]*/Service.svc">https://10.41.69.77/RichchannelWS/service.svc</serviceUrl>
        </build>
        <build type="client.qa">
            <serviceUrl regexp="[a-zA-Z0-9_\-\.]*://[a-zA-Z0-9_\.-]*/RichChannel[0-9a-zA-Z]*/Service.svc">https://10.41.69.77/RichchannelWS/service.svc</serviceUrl>
        </build>
        <build type="stage">
            <serviceUrl regexp="[a-zA-Z0-9_\-\.]*://[a-zA-Z0-9_\.-]*/RichChannel[0-9a-zA-Z]*/Service.svc">https://10.41.69.77/RichchannelWS/service.svc</serviceUrl>
        </build>
        <build type="release">
            <serviceUrl regexp="[a-zA-Z0-9_\-\.]*://[a-zA-Z0-9_\.-]*/RichChannel[0-9a-zA-Z]*/Service.svc">https://10.41.69.77/RichchannelWS/service.svc</serviceUrl>
        </build>
    </builds>
</settings>

我想要做的是使用powershell来获取serviceUrl的内容,其中build type =“stage”。

我写了一段PowerShell代码来执行此操作:

$apktype = $args[0]
$xml = [xml](Get-Content .\Licensed\Mobile\JenkinsBuildScripts\prebuildsetting_url_ver.xml)
$newUrl = $xml.settings.builds.build | ? {$_.type -eq $apktype} | select serviceUrl

然后,我在powershell中运行命令并传递参数:

test.ps1 stage

这只是一个简单的代码。但是,当我尝试回显$ newUrl以查看其值时,它不会返回带有type =“stage”的build标记下的serviceUrl值。

任何人都有一些想法?我在互联网上阅读了大量样本,但看不出任何不同。

提前致谢。

2 个答案:

答案 0 :(得分:2)

我相信这就是你要找的东西:

$newUrl = ($xml.settings.builds.build | ? {$_.type -eq $apktype} |select -expand serviceUrl).innerText

即使你获得了<serviceUrl>节点,你真正想要的是该节点的innerText

还要记住,变量$ newUrl在test.ps1脚本之外是不可用的。您可以对变量进行范围调整,也可以使用“dot-source”运算符运行脚本:

. test.ps1 stage

注意前面的.

答案 1 :(得分:1)

我建议改为使用Select-Xml

function Get-ServiceUrl {
param (
    [string]$BuildType = 'stage',
    [string]$Path = '.\Licensed\Mobile\JenkinsBuildScripts\prebuildsetting_url_ver.xml'
)

    $Nodes = Select-Xml -Path $Path -XPath "//build[@type = '$BuildType']/serviceUrl"
    foreach ($Node in $Nodes) {
        $Node.Node.InnerText
    }

}

Get-ServiceUrl
Get-ServiceUrl -BuildType release