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...

JeffreyXu
  • 95
  • 1
  • 6

1 Answers1

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');
  • Thanks @Trevor. I've now discovered the reason the xPath methods are not working is because of the xmlns namespace (). Do you have any idea how to solve that? – JeffreyXu May 24 '12 at 00:43
  • @RandomStranger You may find this helpful --> http://stackoverflow.com/questions/8963328/how-do-i-use-powershell-to-add-remove-references-to-a-csproj – Andy Arismendi May 24 '12 at 01:02