使用 PowerShell 更改 XML 元素值 [英] Change XML Element value with PowerShell

查看:57
本文介绍了使用 PowerShell 更改 XML 元素值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在 StackOverflow 上找到有关如何更改 XML 元素的属性值的内容.

I'm only finding stuff on how to change the attribute values of a XML element here on StackOverflow.

但是我们如何使用 PowerShell 更改元素本身的值?

But how do we change the value of the element itself using PowerShell?

我目前拥有:

XML

<Task>
  <Settings>
  ...
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>blablabla</Command>
      <Arguments>CHANGETHISVALUE</Arguments>
    </Exec>
  </Actions>
</Task>

脚本

$filePathToTask = C:\Task.xml
$xml = New-Object XML
$xml.Load($filePathToTask)
$element =  $xml.SelectSingleNode("//Arguments")
$element.InnerText("newtext")
$xml.Save($filePathToTask)

但是,我似乎无法对最后一个变量使用方法.我做错了什么?

However, I can't seem to use methods on the last variable. What am I doing wrong?

编辑

  • 添加代码

我得到的错误是您不能在空值表达式上调用方法

我认为我的问题在于:

$ElementToChange =  $xml.SelectSingleNode("//Arguments")

它保持为空,但我尝试过像 .SelectNodes 这样的方法并使用 //Arguments 标签,但仍然没有成功

Which stays null, but I have tried methods like .SelectNodes and playing around with the //Argumentstag but still no success

推荐答案

InnerText 是一个属性,而不是一个方法.它是这样使用的:

InnerText is a property, not a method. It's used like this:

$element.InnerText = "newtext"

此外,我怀疑您的原始数据(与您发布的 XML 示例不同)使用了命名空间.AFAICS 这是 $xml.SelectSingleNode('//Arguments') 返回空结果的唯一可能原因.从 Windows 任务计划程序导出的 XML 文件肯定是命名空间的:

Also, I suspect that your original data (unlike the XML sample you posted) uses namespaces. AFAICS that's the only possible reason why $xml.SelectSingleNode('//Arguments') would return an empty result. XML files exported from the Windows Task Scheduler definitely are namespaced:

<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task‌​">
  <!-- ... -->
</Task>

命名空间与其他节点属性不同,它不仅影响节点本身,还影响其子节点.要从具有命名空间的 XML 中选择节点,您需要一个命名空间管理器:

Namespaces are not like other node attributes and affect not only the node itself, but also its child nodes. For selecting nodes from an XML with namespaces you need a namespace manager:

$nsm = New-Object Xml.XmlNamespaceManager($xml.NameTable)
$nsm.AddNamespace('ns', $xml.DocumentElement.NamespaceURI)
$element = $xml.SelectSingleNode('//ns:Arguments', $nsm)

这篇关于使用 PowerShell 更改 XML 元素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆