by vmusunoor at 2013-05-07 11:16:44
Hi,by vmusunoor at 2013-05-07 12:48:07
i’m trying to add xml node to existing xml file…
xml node to be added
<device>|Test|#12!test_res|#12!Test|#12!D:\MSSQL\DATA|#12!D:\MSSQL\DATA.mdf</device>
<device>|Test|#12!test_res|#12!Test|#12!L:\MSSQL\LOG|#12!D:\MSSQL\DATA.ldf</device>
xml file and path :
[xml]$temp = Get-Content C:\temp\template.xml
$temp.xml.TMMsg_CreateTaskReq.taskinfo.subTasks.options.restoreOptions.sqlServerRstOption
please let me know how to add it…
Thanks
I tried with the following scriptby eisenbergz at 2013-05-08 07:54:23
[string]$dev = <device>|CAForms|#12!testCDC|#12!CAForms|#12!D:\MSSQL\DATA|#12!D:\MSSQL\DATA\CAForms.mdf</device>
<device>|CAForms|#12!testCDC|#12!CAForms_log|#12!L:\MSSQL\LOG|#12!D:\MSSQL\DATA\CAForms.ldf</device>
[xml]$temp = Get-Content C:\temp\template.xml
$temp.xml.TMMsg_CreateTaskReq.taskinfo.subTasks.options.restoreOptions.sqlServerRstOption.device.Appendchild([string]$dev);
$temp.Save("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
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)
$xmlfile.SelectNodes($path)
}
Function New-XmlNode
{
param($xmlfile, $node, $nodeName)
$tmp = $xmlfile.CreateElement($nodeName)
$node.AppendChild($tmp)
}
[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")
$tmp.set_InnerXML("|CAForms|#12!testCDC|#12!CAForms|#12!D:\MSSQL\DATA|#12!D:\MSSQL\DATA\CAForms.mdf")
$RstOption.AppendChild($tmp)
$temp.Save("C]
(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?