Search code examples
xmlpowershellmergeaddition

How to appen new elements into XML using powershell


I need to create new tag within XML file and then fill the new tag with new elements. I will do this multiple times in one script. I am able to create the new tag but when i try to fill it with new elements i get an error.

My code so far:

$file = "filepath"
[System.Xml.XmlDocument]$xmlObject = New-Object System.Xml.XmlDocument
$xmlObject = [System.Xml.XmlDocument](Get-Content $file)

#first i add the <authorization> tag
$newXmlElement = $xmlObject.CreateElement('authorization')
$newXmlElement.InnerText = ""
$xmlObject.configuration.AppendChild($newXmlElement)

#then i try to fill the tag with more data
$newXmlElement = $xmlObject.CreateElement('deny')
$newXmlElement.SetAttribute('users', '?')
$xmlObject.configuration.authorization.AppendChild($newXmlElement)

When i try to call the new tag in last line of code i get this error: Method invocation failed because [System.String] does not contain a method named 'AppendChild'

How would i go about filling the new tag with new element? Desired result:

<configuration>
     <authorization>
          <deny users="?" />
     </authorization>
</configuration>

Solution

  • I would use xpath and fragment in this case:

    $newelem=@'
         <authorization>
              <deny users="?" />
         </authorization>
    '@
    
    $dest = $xmlObject.SelectSingleNode('//configuration') 
    $xmlFragment=$xmlObject.CreateDocumentFragment()
    $xmlFragment.InnerXML=$newelem
    $dest.AppendChild($xmlFragment)
    

    This works for your simplified xml in the question and you may have to modify it to fit your actual xml file.