1

PowerShell/xml beginner here.... I'm trying to append to or remove empty xml nodes using PowerShell as part of a Nuget Package. The xml file has the following format...

<Root>
    <service name="first">
        <item>
        </item>
    </service>
    <service name ="second">
        <item>
        </item>
    </service>
</Root>

First my script select one of the services and save it as a variable, say if the user wants to select service 1.....

if ($xml.Root.service.name -eq $serviceName)
{
         $myService = $xml.Root.service
}

Problem is later on, I need to append elements to the node/delete the node... I have something like

    $newNode = $xml.CreateElement('new'...
    .........

    $empty = $myService.SelectSingleNode('./item')
    $empty.PrependChild($newNode)

But I can't get the this method to work.

Any suggestions would be appreciated...

1 Answer 1

4

This should help you out.

# Get an XML document
$MyXml = [xml]'<?xml version="1.0" encoding="utf-8"?><root><service name="foo"><item></item></service></root>';
# Create a new element from the XmlDocument object
$NewElement = $MyXml.CreateElement('new');
# Select the element that we're going to append to
$ServiceElement = Select-Xml -Xml $MyXml -XPath '/root/service[@name="foo"]/item';
# Append the 'new' element to the 'item' element
$ServiceElement.AppendChild($NewElement);
# Echo the OuterXml property of the $MyXml variable to verify changes
Write-Host -Object $MyXml.OuterXml;
# Save the XML document
$MyXml.Save('c:\test.xml');
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Trevor. I've now discovered the reason the xPath methods are not working is because of the xmlns namespace (<root xmlns = "www...."/>). Do you have any idea how to solve that?
@RandomStranger You may find this helpful --> stackoverflow.com/questions/8963328/…

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.