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 !
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 ;)
I'd suggest that using appendChild
is your problem - it appends the node to the end of the list.
Prehaps you could use InsertBefore
or InsertAfter
instead (assuming you can get a reference to a node either side of the desired insertion point.
See MSDN for docs on InsertAfter or InsertBefore.
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