Tuesday, 29 June 2010

Clone-XMLNode.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script clones an XML element. 
  4. .DESCRIPTION 
  5.     This script creates an XML document, then creates two 
  6.     clone elements. 
  7. .NOTES 
  8.     File Name  : Clone-XMLNode.ps1 
  9.     Author     : Thomas Lee - tfl@psp.co.uk 
  10.     Requires   : PowerShell Version 2.0
  11.                  Needs PowerShell Community Extensions too! 
  12. .LINK 
  13.     This script posted to: 
  14.         http://www.pshscripts.blogspot.com 
  15.     MSDN Sample posted at: 
  16.         http://msdn.microsoft.com/en-us/library/system.xml.xmlelement.removeattributeat.aspx 
  17. .EXAMPLE 
  18.     PSH [C:\foo]: .\CloneXMLNode.ps1 
  19.     <book genre="novel" ISBN="1-861001-57-5"
  20.       <title>Pride And Prejudice 
  21.       <misc publisher="WorldWide Publishing">hardcover</misc> 
  22.       <misc publisher="WorldWide Publishing">hardcover</misc> 
  23.       </title> 
  24. </book> 
  25. #> 
  26.      
  27. $Doc = New-Object System.Xml.XmlDocument 
  28. $Doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>"
  29.                 "<title>Pride And Prejudice</title>"
  30.              "</book>"            
  31.              ) 
  32.               
  33. # Create an element 
  34. $elem = $doc.CreateElement("misc"
  35. $elem.InnerText = "hardcover" 
  36. $elem.SetAttribute("publisher", "WorldWide Publishing"
  37.  
  38.  # Clone the element so we can add one to each of the book nodes. 
  39. $elem2 = $elem.CloneNode($true
  40.  
  41. # Add the new elements. 
  42. $result = $doc.DocumentElement.FirstChild.AppendChild($elem
  43. $result = $doc.DocumentElement.LastChild.AppendChild($elem2
  44.  
  45.  
  46. # Display the Modified XML..." 
  47. $doc.InnerXml | format-xml 

1 comment:

php expert group said...

This post is really appreciable and very informative. This is giving me great information. Thanks for posting.

Clone Script