xml - How to insert a child node in Powershell when parent is empty -


from :

<products> </products> 

i want :

<products>     <product code="id1"> </products> 

what's right syntax ? tried not seem work :

$newproduct= $products.createelement("product") $newproduct.setattribute("code", "");                         $newproduct.code="id1"  $products.appendchild($newproduct) 

solution given below works except appendchild not work on null value. i've typed given example on powershell 2.

enter image description here

create attribute node , append <product> node's attributes:

[xml]$xml = '<products></products>'  $newproduct = $xml.createelement('product') $attr = $xml.createattribute('code') $attr.value = 'id1' $newproduct.attributes.append($attr)  $products = $xml.selectsinglenode('//products') $products.appendchild($newproduct) 

result:

<?xml version="1.0" encoding="ibm850"?> <products>   <product code="id1" /> </products> 

demonstration (powershell v2):

ps c:\> $psversiontable  name                           value ----                           ----- clrversion                     2.0.50727.3662 buildversion                   6.0.6002.18111 psversion                      2.0 wsmanstackversion              2.0 pscompatibleversions           {1.0, 2.0} serializationversion           1.1.0.1 psremotingprotocolversion      2.1  ps c:\> [xml]$xml = '<products></products>' ps c:\> $newproduct = $xml.createelement('product') ps c:\> $attr = $xml.createattribute('code') ps c:\> $attr.value = 'id1' ps c:\> $newproduct.attributes.append($attr)  #text ----- id1  ps c:\> $products = $xml.selectsinglenode('//products') ps c:\> $products.appendchild($newproduct)  code ---- id1  ps c:\> $xml.save([console]::out) + "`n" <?xml version="1.0" encoding="ibm850"?> <products>   <product code="id1" /> </products>

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -