Powershell: add child node in XML -


i have following xml tree:

<company>   <employees>     <employee name="dwight" id="e1000" department="sales">     </employee>     <employee name="toby" id="e1001" department="hr">     </employee>     <employee name="jim" id="e1002" department="sales">     </employee>     <employee name="pam" id="e1003" department="reception">     </employee>   </employees> </company> 

i add child named "address" under each employee , under "address", add different children named "housenumber", "street" , "zip"

this i've tried far, add "address" child:

$filename = "c:\code\employees.xml"; $xmldoc = [system.xml.xmldocument](get-content $filename);  $newxmlemployee = $xmldoc.company.employees.employee.appendchild($xmldoc.createelement("address")) $xmldoc.save($filename); 

however i'm greeted following error messages:

method invocation failed because [system.object[]] doesn't contain method named 'appendchild'. @ c:\code\testing.ps1:10 char:64 + $newxmladdress = $xmldoc.company.employees.employee.appendchild <<<< ($xmldoc.createelement("address")); + categoryinfo : invalidoperation: (appendchild:string) [], runtimeexception + fullyqualifiederrorid : methodnotfound

how resolve this?

you have iterate on each node , create address node each of them:

$filename = "c:\code\employees.xml"; $xmldoc = [system.xml.xmldocument](get-content $filename);  $xmldoc.company.employees.employee | foreach-object {         $_.appendchild($xmldoc.createelement("address"))     } $xmldoc.save($filename); 

output:

<company>   <employees>     <employee name="dwight" id="e1000" department="sales">       <address />     </employee>     <employee name="toby" id="e1001" department="hr">       <address />     </employee>     <employee name="jim" id="e1002" department="sales">       <address />     </employee>     <employee name="pam" id="e1003" department="reception">       <address />     </employee>   </employees> </company> 

if need more subchildren, assign output of appendchild variable , use append them.


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -