I’m attempting to build an array of [XElement] objects as demonstrated in the .Net docs, and add them to an XMLTree using LINQ.
I’m a .foreach{}
loop person, and being a for each loop person the way to do this seemed obvious:
[Array]$Array = (0..2).foreach{ [XElement]::new("test", "test") }
All that was left was to add it to the XML tree
$Query = [XElement]::new('root', [XElement]::new("parameters", $Array))$Query.ToString()
<root> <parameters><test>test</test><test>test</test><test>test</test></parameters> </root>Malformatted :( After a bunch of testing and dismay, I realized it was passing the Array as a string to the [XElement] constructor, which results in the encoding of the brackets. You can test this by using
[XElement]::Parse()
on the first index of the Array, and it outputs in the well-formatted and correct manner.
[XElement]::new("parameters",[XElement]::parse($Array[0])}This is only an issue when using the .foreach() operator.
Any other variation of foreach does not have the issue:
$Array = foreach ($i in 0..2) { [XElement]::new("test", "test") }$Query = [XElement]::new(‘root’, [XElement]::new(“parameters”, $Array)
)
$Query.ToString()
$Array = 0..2 | ForEach-Object { [XElement]::new("test", "test") }$Query = [XElement]::new(‘root’, [XElement]::new(“parameters”, $Array)
)
$Query.ToString()
Output:
<root> <parameters> <test>test</test> <test>test</test> <test>test</test> </parameters> </root>
BUT…
If the array is instantiated first, and then each individual [XElement] obj is added to the array using += operator. It works as expected.
$Array = @()(0…2).foreach{ $Array += [XElement]::new(“test”, “test”) }
$Query = [XElement]::new(‘root’, [XElement]::new(“parameters”, $Array)
)
$Query.ToString()
<root> <parameters> <test>test</test> <test>test</test> <test>test</test> </parameters> </root>The only thing that looks different is that if you look at the BaseObject property of the psobject. You will see the following:
$Array = (0..2).foreach{ [XElement]::new("test", "test") }$Array.psobject
…
BaseObject : {<test>test</test>, <test>test</test>, <test>test</test>}
$Array = foreach ($i in 0..2) { [XElement]::new("test", "test") }$Array.psobject
…
BaseObject : {test, test, test}
What is causing this behavior?
Please note that this behavior happens before the array of [XElements] are added to the Root XMLTree in the examples.