Powershell 计算后更新XML节点值

Powershell 计算后更新XML节点值,powershell,powershell-2.0,Powershell,Powershell 2.0,我的XML如下所示 <Components> <Component> <Name>Comp1</Name> <Baseline>Comp1_2.1.0.20.2824</Baseline> <KLOC>0</KLOC> <IsCount>True</IsCount> </Component> <Component

我的XML如下所示

<Components>
  <Component>
    <Name>Comp1</Name>
    <Baseline>Comp1_2.1.0.20.2824</Baseline>
    <KLOC>0</KLOC>
    <IsCount>True</IsCount>
    </Component>
  <Component>
    <Name>Comp2</Name>
    <Baseline>Comp2_2_7_2012.3171</Baseline>
    <KLOC>0</KLOC>
    <IsCount>True</IsCount>
  </Component>
</Components>

现在我想将KLOC存储在相应的组件KLOC标记中。

使用一点XPath,您可以获得text()节点的句柄并设置其值

更新:要根据解析文件的名称使Xpath查询动态化,可以使用
GetFileNameWithoutExtension
方法。只要文件名与XML中的组件名匹配,这就可以工作。添加代码以检索
foreach
循环中的
$count
变量

$doc = [xml] (Get-Content "C:\InputFile.xml")
$compFiles = 'Comp1.log', 'Comp2.log'

foreach ($file in $compFiles) {

    # Get $count from $file here...

    $compName = [IO.Path]::GetFileNameWithoutExtension($file)
    $xpath = "//Component[Name='${compName}']/KLOC/text()"
    $node = $doc.SelectSingleNode($xpath)
    $node.Value = $count
}

$doc.Save("C:\Output.xml")

我对这个问题做了一些澄清。如果可能的话,请帮助我out@Samselvaprabu我根据您增加的要求更新了我的答案。
$doc = [xml] (Get-Content "C:\InputFile.xml")
$compFiles = 'Comp1.log', 'Comp2.log'

foreach ($file in $compFiles) {

    # Get $count from $file here...

    $compName = [IO.Path]::GetFileNameWithoutExtension($file)
    $xpath = "//Component[Name='${compName}']/KLOC/text()"
    $node = $doc.SelectSingleNode($xpath)
    $node.Value = $count
}

$doc.Save("C:\Output.xml")