Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - Insert node between two others

Tags:

powershell

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 !

like image 706
Xavier Avatar asked Dec 05 '22 03:12

Xavier


2 Answers

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 ;)

like image 95
stej Avatar answered Jan 17 '23 05:01

stej


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.

like image 23
Grhm Avatar answered Jan 17 '23 04:01

Grhm