更新xml文档中的数组元素

时间:2017-04-05 00:28:31

标签: powershell powershell-v5.0

此代码:

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

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

产量:

World

然后这段代码:

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

产量:

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

为什么第二个Child节点未从World更新为StackOverflow

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

$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

发生了什么事?

1 个答案:

答案 0 :(得分:1)

似乎与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" = "StackOverflow"
$xml.Test.Child[1]                      # = StackOverflow