如何更新System.Xml.XmlDocument中的节点值?

时间:2015-09-18 23:58:23

标签: xml powershell xpath

在PowerShell v3中,我创建了一个像这样的XmlDocument对象:

[System.Xml.XmlDocument]$xmldoc = new-object System.Xml.XmlDocument
$xmldoc.Load($xmlfile)

经过一些处理后,我想让用户更新$xmlfile中节点的值。

考虑到要分配的节点名称和新值,如何更新$xmldoc

$node = StartBoundry
$newvalue = StringValue

我知道我可以这样保存:

$xmldoc.Save($xmlfile)

原始XML看起来像这样:

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Author>MYDOMAIN\user.name</Author>
    <Description>my description</Description>
  </RegistrationInfo>
  <Triggers>
    <TimeTrigger>
      <Repetition>
        <Interval>PT2M</Interval>
        <StopAtDurationEnd>false</StopAtDurationEnd>
      </Repetition>
      <StartBoundary>2015-09-18T09:29:14</StartBoundary>
      <Enabled>true</Enabled>
      <RandomDelay>PT3S</RandomDelay>
    </TimeTrigger>
  </Triggers>
...

我已经尝试过这样的XPath:

$ns = @{'ns'='http://schemas.microsoft.com/windows/2004/02/mit/task'}
$xml = Select-Xml -Xml $xmldoc -XPath "//ns:Task/ns:Triggers/ns:TimeTrigger/ns:StartBoundary" -Namespace $ns
$xml.Node.Value = $newvalue

但如果我拥有的是节点名称,如何获取路径?有没有方法可以做到这一点,或者我必须迭代所有元素,直到找到节点名称匹配?

2 个答案:

答案 0 :(得分:1)

这似乎有效......

[System.Xml.XmlDocument]$xmldoc =  New-Object System.Xml.XmlDocument
$xmldoc.Load($xmlfile)
# user selects node, provides $newvalue
[System.Xml.XmlNode]$xmlnode = $xmldoc.GetElementsByTagName($node)[0].ChildNodes[0]
$xmlnode.InnerText = $newvalue
$xmldoc.Save($xmlfile)

答案 1 :(得分:0)

将您的XPath修改为:

$node = 'StartBoundary'
$xmlInfo = Select-Xml -Xml $xmldoc -XPath "//ns:$node" -Namespace $ns
$xmlInfo.Node.Value = $newvalue
相关问题