Powershell - Insert a node between two other

I would like to insert a node between two existing ones. In my script, I get the xml variable and I would like to update it.

Example:

<mapping ...>
    <INSTANCE .. />
    <INSTANCE .. />
    <CONNECTOR .. />
    <CONNECTOR .. />
</mapping>

the result should be:

<mapping ...>
    <INSTANCE .. />
    <INSTANCE .. />
    <NEWINSERT .../>
    <CONNECTOR .. />
    <CONNECTOR .. />
</mapping>

When I use appendChild, the insert is always done at the end ...

Idea?

Thank!

+3
source share
2 answers

As @Grhm replied, you can do this with InsertAfter. I would recommend always trying to connect it to Get-Memberto get a 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 that gm(or Get-Member) is the most useful cmdlet in PowerShell;)

+11
source

I would suggest that use appendChildis your problem - it adds node to the end of the list.

, InsertBefore InsertAfter (, node .

. MSDN InsertAfter InsertBefore.

+4

Source: https://habr.com/ru/post/1731356/


All Articles