Why does this PowerShell Script not work:
[xml]$xml = '<products></products>'
$newproduct = $xml.CreateElement('product')
$attr = $xml.CreateAttribute('code')
$attr.Value = 'id1'
$newproduct.Attributes.Append($attr)
$products = $xml.products
$products.AppendChild($newproduct)
Error is
Method invocation failed because [System.String] does not contain a method named 'AppendChild'.
At line:1 char:1
+ $products.AppendChild($newproduct)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
If I replace
$products = $xml.products
by
$products = $xml.SelectSingleNode('//products')
it will work, but I'd like to know why first syntax does not work because it is illogical for me. $xml.products
should be a valid XML object and thus provide the method AppendChild()
.
$xml.products
does not reference the products
node itself, but the contents of the products
node. Since products
is empty, it evaluates to an empty string.
To get to the products
node you could also use:
$Products = $xml.FirstChild
$Products.AppendChild($newproduct)
or, more specifically:
$Products = $xml.ChildNodes.Where({$_.Name -eq "products"}) |Select-Object -First 1
$Products.AppendChild($newproduct)
But SelectSingleNode()
will probably serve you just fine
$xml.configuration.SelectSingleNode("connectionStrings").AppendChild($newnode)
would work fine, but an interesting & dirty hack: given this empty node:
<connectionStrings>
</connectionStrings>
the script
$xml.configuration.connectionStrings.AppendChild($newnode)
gives a "Method invocation failed because [System.String] does not contain a method named 'AppendChild'
" error
but this:
<connectionStrings>
<!-- random comment -->
</connectionStrings>
works perfectly fine
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With