Question:
Why does this PowerShell Script not work:
1 2 3 4 5 6 7 8 9 10 |
[xml]$xml = ' $newproduct = $xml.CreateElement('product') $attr = $xml.CreateAttribute('code') $attr.Value = 'id1' $newproduct.Attributes.Append($attr) $products = $xml.products $products.AppendChild($newproduct) |
Error is
1 2 3 4 5 6 7 |
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
1 2 |
$products = $xml.products |
by
1 2 |
$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()
.
Answer:
$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:
1 2 3 |
$Products = $xml.FirstChild $Products.AppendChild($newproduct) |
or, more specifically:
1 2 3 |
$Products = $xml.ChildNodes.Where({$_.Name -eq "products"}) |Select-Object -First 1 $Products.AppendChild($newproduct) |
But SelectSingleNode()
will probably serve you just fine