Automating the world one-liner at a time…
While it’s very easy to load and view the content of XML documents how do you add new elements? Here’s how:
Let’s create a simple XML document, one parent node with two children:
PS> [xml]$x = “<top>
<first>first child</first>
<second>second child</second>
</top>”
PS> $x.top
first second----- ------first child second child
Add a new element below our top element with textual content:
PS> $e = $x.CreateElement("third")PS> $e.set_InnerText("third child")
(Windows PowerShell wraps .Net object properties with method calls. The method set_InnerText actually refers to the .Net property InnerText, and is required because our XML adapter assumes that all properties come from your XML)
PS> $x.top.AppendChild($e)
What does our XML look like now?
first second third----- ------ -----first child second child third child
That’s it!
Nigel Sharples [MSFT]Windows PowerShell TeamMicrosoft CorporationThis posting is provided "AS IS" with no warranties, and confers no rights.
Thanks for sharing this example, but... what's with your signature ? :))
I've noticed that if your $x started out as simply "<top/>" (ie no child elements) this does not work.
This is because $x.top evaluates as a string, and so has no AppendChild method.
You can, however, use $x["top"].AppendChild(...)
Would that be a bug? If not, should the latter syntax be preferred as you may never know for sure if you have any child elements.
$x["top"].AppendChild(...), good point
Thanks for the solution Adrian. That was exactly my problem.