更新XML节点即使它是空的

时间:2014-12-02 18:12:10

标签: xml powershell octopus-deploy

我已经获得了以下PowerShell代码,可以使用Octopus Deploy中的值更新xml节点。

    foreach($key in $OctopusParameters.Keys)
    {
        $myXPath = "$nodeXPath/$($key.Replace(".", "/"))"
        try{
            $node = $doc.SelectSingleNode($myXPath)
        } catch { <# sometimes Octopus passes in crappy data #> }
        if($node){
            Write-Host "Overriding node: '$key'`t`t With value: $($OctopusParameters["$key"])"
            $node.'#text' = $OctopusParameters["$key"]
        }
    }

它工作得很好,但前提是原始xml节点有值。

<something>Replaced_by_octopus</something>  <!-- I work -->
<something></something>                     <!-- I fail -->

失败发生在$node.'#text' = $OctopusParameters["$key"]行,并显示以下错误消息

  

Get-EnvironmentSettings:异常设置&#34; #text&#34;:&#34;属性&#39; #text&#39;在这个对象上找不到。验证   该属性存在且可以设置。&#34;

我需要做些什么才能更新该节点,无论它是否为空?

1 个答案:

答案 0 :(得分:0)

您可以使用属性$node.'#text'

,而不是设置InnerText
    foreach($key in $OctopusParameters.Keys)
    {
        $myXPath = "$nodeXPath/$($key.Replace(".", "/"))"
        try{
            $node = $doc.SelectSingleNode($myXPath)

            if($node){
                Write-Host "Overriding node: '$key'`t`t Value: '$($OctopusParameters["$key"])'"
                $node.InnerText = $($OctopusParameters["$key"])
            }
        } catch { 
            <# sometimes Octopus passes in crappy data #> 
        } finally {
            $node = $null
        }
    }