2010-02-04 8 views
3

Je voudrais insérer un noeud entre 2 autres déjà existants. Dans mon script, je reçois une variable xml et je voudrais mettre à jour celle-ci.Powershell - Insérer un noeud entre deux autres

Ex:

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

le résultat devrait être:

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

Lorsque j'utilise un appendChild, l'insert est fait toujours fait à la fin ...

Une idée?

Merci!

Répondre

4

Je suggère que l'utilisation de appendChild est votre problème - il ajoute le nœud à la fin de la liste.

Prehaps vous pouvez utiliser InsertBefore ou InsertAfter à la place (en supposant que vous pouvez obtenir une référence à un nœud de chaque côté du point d'insertion souhaité.

Voir MSDN pour docs sur InsertAfter ou InsertBefore.

11

Comme @Grhm répondu, vous pouvez le faire par InsertAfter. Je recommande toujours d'essayer de tuyau à Get-Member pour obtenir le soupçon.

> $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 

Personnellement, je pense que gm (ou Get-Member) est l'applet de commande la plus utile dans PowerShell;)

+1

Oui, mes quatre grandes applets de commande sont: Get-Help, Get-Command, Get-Member et Get-PSDrive. Les quatre clés du royaume PowerShell. :-) –

Questions connexes