Q:

Simple way to copy node from existing XML-File to New XML-File

I have an existing (source-)XML file which looks like this:
<? xml version="1.0" encoding="utf-8"? >
<Base>
  <Meta>
    <Element>Value</Element>
  </Meta>
  <Settings>
    <Hostname>Computer01</Hostname>
  </Settings>
  <Data>
    <Element>Value</Element>
  </Data>
</Base>

I import this XML-file to the Variable "$Xml" with the following PowerShell-Code:
$Xml = New-Object -TypeName System. Xml. XmlDocument ; $Xml. Load( $PathToXml )

I want to export/save the <Settings> node (+children) from $Xml to a new XML-File, that does not exist yet. 
As for this example the new destination-XML file should look somehow like this:
<? xml version="1.0" encoding="utf-8"? >
<Base>
  <Settings>
    <Hostname>Computer01</Hostname>
  </Settings>
</Base>

My temporary solution is to copy over the whole source-xml and select and remove the unwanted nodes, but this is not a clean solution.  I also tried to build up a new XML from scratch, but that used a lot of code and I am sure, there is a cleaner and simpler way to get this task done. 
Thank you in advance

A:

The following will accomplish what you need if you are okay with using XPath syntax. 
$xml = [xml](Get-Content source.xml)
$Nodes = $xml. SelectNodes('Base/*[name() ! = "Settings"]')
foreach ($Node in $Nodes) {
    [void]$xml. Base. RemoveChild($Node)
}
$xml. Save("c:\temp\destination.xml")

An alternative, relying on the where() method to find the node names to remove, is the following. 
$xml = [xml](Get-Content source.xml)
$NodesToRemove = $xml. Base. ChildNodes. Name.where{$_ -ne 'Settings'}
foreach ($NodeName in $NodesToRemove) {
    $node = $xml. Base. SelectSingleNode($NodeName)
    [void]$xml. Base. RemoveChild($node)
}
$xml. Save("c:\temp\destination.xml")

Explanation:
$xml stores the XML contents as an XmlDocument type by use of the [xml] type accelerator.  $NodesToRemove is an array that holds the names of all child nodes of Base not named Settings.  Then the nodes matching the names within the array are found and subsequently removed.  Save() is used to store the updated XML content.