1

I want to remove some parent nodes from a XML document but keep the children. For example:

I have this structure:

<?xml version="1.0"?>
<ns:root xmlns:ns="ns">
    <ns:node1>
        <ns:node2>
            <ns:node3>
            </ns:node3>
            <ns:node4>
            </ns:node4>
        </ns:node2>
    </ns:node1>
</ns:root>

and want to get this:

<?xml version="1.0"?>
<ns:node2 xmlns:ns="ns">   <!-- new root -->
    <ns:node3>
    </ns:node3>
    <ns:node4>
    </ns:node4>
</ns:node2>

My current script looks like this:

# Get the content as xml
$xml = [xml] (gc c:\test.xml)


# Grab the namespace
$namespaceMgr = New-Object System.Xml.XmlNamespaceManager $xml.NameTable
$namespace = $xml.DocumentElement.NamespaceURI
$namespaceMgr.AddNamespace("ns", $namespace)

# Select node2
$xml.SelectSingleNode('/ns:root/ns:node1/ns:node2', $namespaceMgr) 

# How to save it now as a new valid xml file?
2
  • Since your code suggests your XML data uses namespaces, your sample data should reflect that. Commented Jun 25, 2014 at 13:04
  • You are right - thanks for correcting Commented Jun 25, 2014 at 13:54

1 Answer 1

1

Remove the existing child elements from the XML objects and append the node you selected before, then write the modified XML object back to a file:

...

$node = $xml.SelectSingleNode('/ns:root/ns:node1/ns:node2', $namespaceMgr)

$xml.RemoveAll()
$xml.AppendChild($node)

$xml.Save('C:\test.xml')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.