更新 xml 文档中的数组元素

Updating array element in xml document

此代码:

$test = @"
<Test>
  <Child>Hello</Child>
  <Child>World</Child>
</Test>
"@

$xml = [xml]$test
$xml.Test.Child[1]

产量:

World

然后这个代码:

$xml.Test.Child[1] = "Whosebug"
$xml.InnerXml

产量:

<Test><Child>Hello</Child><Child>World</Child></Test>

为什么第二个 Child 节点没有从 World 更新到 Whosebug

好的,让我们尝试一些不同的东西:

$ipaddress=([System.Net.DNS]::GetHostAddresses($hostname)|Where-Object {$_.AddressFamily -eq "InterNetwork"}   |  select-object IPAddressToString)[0].IPAddressToString

现在我想知道 $ipaddress 的类型是什么:

$ipaddress.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

显然是字符串。

$xml.Test.ChildNodes[1].'#text' = $ipaddress
Cannot set "#text" because only strings can be used as values to set XmlNode properties.
At line:1 char:1
+ $xml.Test.ChildNodes[1].'#text' = $ipaddress
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], SetValueException
    + FullyQualifiedErrorId : XmlNodeSetShouldBeAString

但是$ipaddress是字符串!

终于成功了:

$xml.Test.ChildNodes[1].'#text' = [string]$ipaddress

怎么回事?

似乎与 PowerShell 6 中可能已修复的错误有关。我手边没有 Linux 机器可以检查。

您会找到该错误的描述 here

同时,如您所见,有一个解决方法:

$test = @"
<Test>
  <Child>Hello</Child>
  <Child>World</Child>
</Test>
"@

$xml = [xml]$test
$xml.Test
$xml.Test.GetType()                 # = XmlElement

$xml.Test.Child[1]                      # = World
$xml.Test.Child[1].GetType()            # = String

$xml.Test.Child[1] = "Tralala"
$xml.Test.Child[1]                      # = World


$xml.Test.ChildNodes.Item(1).GetType()  # = XmlElement
$xml.Test.ChildNodes.Item(1)."#text" = "Whosebug"
$xml.Test.Child[1]                      # = Whosebug