2010-02-04 61 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

相关问题