Powershell - Insert node between two others
powershell
Solution
As @Grhm answered, you can do it by `InsertAfter`. I would recommend always to try to pipe it to `Get-Member` to get the hint.
> $x = [xml]@"
<mapping>
<INSTANCE a="abc" />
<INSTANCE a="abc" />
<CONNECTOR a="abc" />
<CONNECTOR a="abc" />
</mapping>
"@
> $x | gm -membertype method
TypeName: System.Xml.XmlDocument
Name MemberType Definition
---- ---------- ----------
AppendChild Method System.Xml.XmlNode AppendChild(System.Xml
..
ImportNode Method System.Xml.XmlNode ImportNode(System.Xml.
InsertAfter Method System.Xml.XmlNode InsertAfter(System.Xml
InsertBefore Method System.Xml.XmlNode InsertBefore(System.Xm
Load Method System.Void Load(string filename), System
...
WriteTo Method System.Void WriteTo(System.Xml.XmlWriter
> $newe = $x.CreateElement('newelement')
> $x.mapping.InsertAfter($newe, $x.mapping.INSTANCE[1])
> $x | Format-Custom
Personally I think `gm` (or `Get-Member`) is the most useful cmdlet in PowerShell ;)
Problem
I would like to insert a node between 2 others already existing. In my script, I receive a xml variable and I would like to update this one. Ex : ``` <mapping ...> <INSTANCE .. /> <INSTANCE .. /> <CONNECTOR .. /> <CONNECTOR .. /> </mapping> ``` the result should be : ``` <mapping ...> <INSTANCE .. /> <INSTANCE .. /> <NEWINSERT .../> <CONNECTOR .. /> <CONNECTOR .. /> </mapping> ``` When I use a appendChild, the insert is done always done at the end... An idea ? Thanks !