2010-02-04 60 views
3

我想在已有的其他人之間插入一個節點。 在我的腳本中,我收到一個xml變量,我想更新這個。Powershell - 在兩個其他人之間插入節點

例:

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

的結果應該是:

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

當我使用的appendChild,插入完成總是在年底完成...

的想法?

謝謝!

回答

4

我建議使用appendChild是你的問題 - 它將節點追加到列表的末尾。

Prehaps可以使用InsertBeforeInsertAfter代替(假定可以得到一個節點或者所需的插入點的側的基準。

參見MSDN對InsertAfterInsertBefore文檔。

11

作爲@Grhm回答,您可以通過InsertAfter做到這一點。我總是建議其嘗試管Get-Member得到提示。

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

我個人認爲gm(或Get-Member)是PowerShell中最有用的cmdlet;)

+1

是的,我的四大命令是:Get-Help,Get-Command,Get-Member和Get-PSDrive。 PowerShell王國的四個鍵。 :-) – 2010-02-04 17:44:04

相關問題