在Powershell中访问XMLAttribute的#text属性 [英] access #text property of XMLAttribute in powershell
问题描述
我有一个格式如下的xml文档:
I have an xml document formated like this:
<root>
<obj>
<indexlist>
<index name="NUMD" value="val1" />
<index name="DATE" value="val2" />
</indexlist>
</obj>
</root>
现在,我想更改将名称设置为"DATE"的索引元素的value属性.我得到这样的属性:
now I'd like to change the value attribute of the index element where name is set to "DATE". I get the attribute like this:
$attr = $xml.selectnodes("//obj/indexlist/index[@name='DATE']/@value")
我可以通过键入以下内容来查看值:
I can view the value by typing this:
$attr.'#text'
但我无法更改:
$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
如何更改XMLAttribute的值?
如果可能的话,我也想坚持使用XPath直接返回属性,因为该脚本的最终用户将使用XPath在配置文件中定义要更改的元素和属性. 还将XPath用作属性时,用户只需提供两个参数即可更改属性和future-value:XPath和value.
I'd also like to stick with XPath returning the attribute directly if that's possible because the end-user of that script will define the elements and attributes to change in a config file using XPath.
While using XPath for the attributes as well the user can simply provide the attribute to change and the future-value with just two arguments: the XPath and the value.
推荐答案
除了#text
,您还可以通过Value
属性访问XmlAttribute
的值:
Besides #text
, you can also access XmlAttribute
's value via Value
property :
$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
请注意,$attr.Value
中的Value
是XmlAttribute
的属性名称.它不受XML中名为value
的属性的影响.
Note that Value
in $attr.Value
is property name of XmlAttribute
. It doesn't affected by the fact that the attribute in your XML named value
.
这篇关于在Powershell中访问XMLAttribute的#text属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!