如何通过读取xml节点值来查找和替换?

时间:2013-07-18 12:55:56

标签: xml powershell powershell-v2.0

以下是我的XML值。

<Components>
    <Component>
        <FullName>CoreEnvironment</FullName>
        <ShortName>CoreEnv</ShortName>
    </Component>
    <Component>
        <FullName>Excel Addin 2007</FullName>
        <ShortName>Excel_07</ShortName>
    </Component>
</Components>

如果用户传递组件的全名,则应显示相应的短名称。我能够使用powershell读取xml中的特定节点。但在这种情况下,如果找到一个FullName节点,则应显示相应的短名称节点。我无法弄清楚这个的逻辑。

2 个答案:

答案 0 :(得分:0)

[xml]$xml="<Components>
    <Component>
        <FullName>CoreEnvironment</FullName>
        <ShortName>CoreEnv</ShortName>
    </Component>
    <Component>
        <FullName>Excel Addin 2007</FullName>
        <ShortName>Excel_07</ShortName>
    </Component>
</Components>"

$test="Excel Addin 2007"

$xml.Components.Component |% { if( $_.fullname -match $test) { write-host  $_.ShortName}}

答案 1 :(得分:0)

类似于Kayasax的答案但使用XPath

[xml] $xml = "<Components>
    <Component>
        <FullName>CoreEnvironment</FullName>
        <ShortName>CoreEnv</ShortName>
    </Component>
    <Component>
        <FullName>Excel Addin 2007</FullName>
        <ShortName>Excel_07</ShortName>
    </Component>
</Components>"

$param = "Excel Addin 2007"

$xml.SelectNodes('//Component') | Where-Object {$_.FullName -eq "$param" } | Select-Object -ExpandProperty ShortName