add node to existing xml file

by vmusunoor at 2013-05-07 11:16:44


i’m trying to add xml node to existing xml file…

xml node to be added


xml file and path :

[xml]$temp = Get-Content C:\temp\template.xml


please let me know how to add it…

by vmusunoor at 2013-05-07 12:48:07
I tried with the following script

[string]$dev = <device>|CAForms|#12!testCDC|#12!CAForms|#12!D:\MSSQL\DATA|#12!D:\MSSQL\DATA\CAForms.mdf</device>

[xml]$temp = Get-Content C:\temp\template.xml

Got the below error…please take a look…

Method invocation failed because [System.String] doesn’t contain a method named ‘Appendchild’.
At C:\Brain\TestPS1.ps1:90 char:109
+ $temp.xml.TMMsg_CreateTaskReq.taskinfo.subTasks.options.restoreOptions.sqlServerRstOption.device.Appendchild <<<< ([string]$dev);
+ CategoryInfo : InvalidOperation: (Appendchild:String) , RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
by eisenbergz at 2013-05-08 07:54:23
Create the element first, put the text in it, then append it to a node (which is an object, not just a string).

See if these functions help you:
Function Get-XmlNode
param($xmlfile, $path)

Function New-XmlNode
param($xmlfile, $node, $nodeName)
$tmp = $xmlfile.CreateElement($nodeName)

[XML]$vInventory = "<Inventory><Roles/><Permissions/></Inventory>"
$XMLRoles = Get-XmlNode $vInventory "Inventory/Roles"
$XMLRole = New-XmlNode $vInventory $XMLRoles "Role"

Maybe this (or a tweaked version of it) will work for you. I don’t have your xml file, so I’m guessing a little. I know it could be a lot prettier.
[xml]$temp = Get-Content C:\temp\template.xml
$RstOption = Get-XmlNode $temp "xml/TMMsg_CreateTaskReq/taskinfo/subTasks/options/restoreOptions/sqlServerRstOption"
$tmp = $temp.CreateElement("device")
(I didn’t use the New-XmlNode function because it didn’t have the .set_InnerXML method in it. Obviously you can mod it as you like.)

…and just to be complete, here’s how to make an attribute:
Function Set-XmlAttribute
param($node, $name, $value)
$node.SetAttribute($name, $value)

How’s that?