Import node from one XML to another on PowerShell

前端 未结 2 1142
傲寒
傲寒 2021-01-25 04:45

I need to copy node with name \"ProjectOptions\" from default.xml to original.xml without modifying anything else:

Original.xml



        
相关标签:
2条回答
  • 2021-01-25 04:50

    You try to insert the imported node under the DocumentElement node, but $Child is not a direct child element of that node. You need to call the InsertAfter() method on the parent node of $Child.

    Change this:

    $xml.DocumentElement.InsertAfter($XML.ImportNode($xmld.SelectSingleNode("//KEY[@ObjectName = 'ProjectOptions']"), $true), $Child)
    

    into this:

    $Child.ParentNode.InsertAfter($XML.ImportNode($xmld.SelectSingleNode("//KEY[@ObjectName='ProjectOptions']"), $true), $Child)
    

    and the problem will disappear.


    As a side note, you may want to use an XPath expression instead of dot-notation for selecting $Child:

    $Child = $xml.SelectSingleNode('//VALUE[@ObjectName="ShowWelcomeMsg"]')
    
    0 讨论(0)
  • 2021-01-25 05:01

    Found a simple way:

    $xmlPO = $xml.SelectNodes("//KEY[@ObjectName='ProjectOptions']")
    $xmldPO = $xmld.SelectNodes("//KEY[@ObjectName='ProjectOptions']")
    $xmlPO.set_InnerXML($xmldPO.innerXML)
    $xml.Save($dpath)​
    
    0 讨论(0)
提交回复
热议问题