wul*_*lxz 5 xml powershell xpath xml-attribute
我有一个xml文档,格式如下:
<root>
<obj>
<indexlist>
<index name="NUMD" value="val1" />
<index name="DATE" value="val2" />
</indexlist>
</obj>
</root>
Run Code Online (Sandbox Code Playgroud)
现在我想更改名称设置为“ DATE”的索引元素的value属性。我得到这样的属性:
$attr = $xml.selectnodes("//obj/indexlist/index[@name='DATE']/@value")
Run Code Online (Sandbox Code Playgroud)
我可以通过键入以下内容来查看值:
$attr.'#text'
Run Code Online (Sandbox Code Playgroud)
但我无法更改:
$attr.'#text' = 'foo'
The property '#text' cannot be found on this object. Verify that the property exists and can be set.
At line:1 char:1
+ $n.'#text' = 'foo'
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
Run Code Online (Sandbox Code Playgroud)
如何更改XMLAttribute的值?
如果可能的话,我也想坚持使用XPath直接返回属性,因为该脚本的最终用户将使用XPath在配置文件中定义要更改的元素和属性。
在将XPath用作属性时,用户只需提供两个参数即可更改属性和future-value:XPath和value。
此外#text,您还可以XmlAttribute通过Value属性访问的值:
$attr = $xml.SelectSingleNode("//obj/indexlist/index[@name='DATE']/@value")
#print old value
$attr.Value
#update attribute value
$attr.Value = "new value"
#print new value
$attr.Value
Run Code Online (Sandbox Code Playgroud)
请注意,Valuein $attr.Value是属性名称XmlAttribute。它不受XML中名为的属性的影响value。