powershellxmldocumentxmlnode

Powershell insert XML here-string into xml document


I'm trying to insert an XML here-string into a XMLdocument. However, the saved XMLdoc, shows: "System.Xml.XmlDocument", not the content. How can I fix this?

[xml] $Doc = New-Object System.Xml.XmlDocument

$updateNode = [xml] "<Update>                       
                          <Request>Test</Request>
                     </Update>"

#Create XML declaration
$declaration = $Doc.CreateXmlDeclaration("1.0","UTF-8",$null)

#Append XML declaration
$Doc.AppendChild($declaration)
    
#Create root element
$root = $Doc.CreateNode("element","BrowseDetailsRequest",$null)

#Create node based on Here-String
$node = $Doc.CreateElement("element",$updateNode,$null)

#Append node
$root.AppendChild($node)
    
#Append root element
$Doc.AppendChild($root)   

Output at this moment:

<?xml version="1.0" encoding="UTF-8"?>
<BrowseDetailsRequest>
  <System.Xml.XmlDocument />
</BrowseDetailsRequest>

Solution

  • You don't really manipulate the text in the xml. Use the objects to manipulate the xml. So you need to create an element for update and request and then assign the innertext value of request.

    $Doc = New-Object System.Xml.XmlDocument
    $declaration = $Doc.CreateXmlDeclaration("1.0","UTF-8",$null)
    $Doc.AppendChild($declaration)
    $root = $Doc.CreateNode("element","BrowseDetailsRequest",$null)
    $elUpdate = $doc.CreateElement("element","Update",$null)
    $elRequest = $doc.CreateElement("element","Request",$null)
    $elRequest.InnerText = "Test"
    $elUpdate.AppendChild($elRequest)
    $root.AppendChild($elUpdate)
    $doc.AppendChild($root)