【问题标题】:How to update node value in System.Xml.XmlDocument?如何更新 System.Xml.XmlDocument 中的节点值?
【发布时间】:2015-09-18 23:58:23
【问题描述】:

在 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

但是如果我只有节点名,如何获取路径?有没有办法做到这一点,还是我必须遍历所有元素,直到找到节点名称匹配?

【问题讨论】:

    标签: xml powershell xpath


    【解决方案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)
    

    【讨论】:

      【解决方案2】:

      鉴于提供的唯一信息是标签名称,您可以使用 XPath descendant-or-self 轴 (//) 和 name() - 或 local-name()- 来匹配 XML 文档中任意位置的目标元素:

      $xmlInfo = Select-Xml -Xml $xmldoc -XPath "//*[name()='StartBoundary']"
      

      【讨论】:

      【解决方案3】:

      将您的 XPath 修改为:

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

      【讨论】:

      • 这是我正在试验的。我还没有测试过,但我认为它应该可以工作。问题是为-Xpath 编写字符串......这就是为什么我正在寻找不需要路径或提供它的方法的解决方案。
      • 所以是的,"//ns:$node""//*[name()='StartBoundary']" 之间没有真正的区别,除了后者不需要命名空间。另外,上面的帖子实际是compose xpath。在$node 中输入您想要的元素名称,XPath 表达式会找到它。与'StartBoundary' 中的硬编码相反。
      猜你喜欢
      • 2013-02-10
      • 1970-01-01
      • 2013-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多