在Powershell中访问XMLAttribute的#text属性

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。

har*_*r07 5

此外#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

  • 实际上,问题是我像您一样使用了selectnodes而不是selectsinglenode。当我只是回声我的`$ attr` powershell时,每次都会向我显示`#text`的值,并且如果我执行`$ attr |也将返回的类型为XmlAttribute。gm`。但是实际上,返回的类型似乎是arrary或collection,它当然没有“ value”属性。将我的方法与$ attr [0] .value`而不是$ attr.value`一起使用也可以,但是正是您的回答和对selectsinglenode的使用使我朝着正确的方向发展;)谢谢:) (2认同)