Unable to return XML from function

This topic contains 2 replies, has 3 voices, and was last updated by  Curtis Smith 3 weeks, 4 days ago.

  • Author
  • #99466



    I'm tring to write function which create custom xml document and return it as XML

    function Create-XML()
        [xml]$Doc = New-Object System.Xml.XmlDocument
        $dec = $Doc.CreateXmlDeclaration("1.0","UTF-8",$null)
        $root = $doc.CreateNode("element","Changes",$null)
        $desc = $doc.CreateNode("element","Description",$null)
        $notes = $doc.CreateNode("element","Notes",$null)
        return ,$Doc

    But every time if I would like to read output from this function I'm getting error: "Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument""

  • #99898

    Matt Howard

    This looks right. It is a "object" now, not the raw XML. How are you trying calling the function?

  • #99901

    Curtis Smith

    Hey Colonel, @fredrik-kacsmarck and @ta11ow already answered this question in your previous post (https://powershell.org/forums/topic/return-xml-from-function/)

    Your AppendChild methods are returning output to the pipleline, so when the function ends it is not just the $xml variable that it returned, it is also all of the output that is returned from the AppendChild methods since you are not doing anything else with it.

    You need to use one of the methods shown by them to do something with the output so that it is not send in the function returned data.

    ID as @fredrik-kacsmarck showed

    function Create-XML()
        [xml]$xml = New-Object System.Xml.XmlDocument
        $Dec = $xml.CreateXmlDeclaration("1.0","UTF-8",$null)
        $Root = $xml.CreateNode("element","Changes",$null)
        return ,$xml

You must be logged in to reply to this topic.