在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
但是,如果我只有节点名,该如何获取路径?有没有执行此操作的方法,或者我必须遍历所有元素,直到找到匹配的节点名称?
最佳答案
鉴于提供的唯一信息是标记名称,因此可以使用XPath descendant-or-self
轴(//
)和name()
-或local-name()
-来匹配XML文档中任何位置的目标元素:
$xmlInfo = Select-Xml -Xml $xmldoc -XPath "//*[name()='StartBoundary']"
关于xml - 如何更新System.Xml.XmlDocument中的节点值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32662718/