Unable to return XML from function

Welcome Forums General PowerShell Q&A Unable to return XML from function

This topic contains 2 replies, has 3 voices, and was last updated by

 
Participant
6 months, 3 weeks ago.

  • Author
    Posts
  • #99466

    Participant
    Points: 0
    Rank: Member

    Hi,

    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)
        $doc.AppendChild($dec)
        
        $root = $doc.CreateNode("element","Changes",$null)
    
        $desc = $doc.CreateNode("element","Description",$null)
        $root.AppendChild($desc)
    
        $notes = $doc.CreateNode("element","Notes",$null)
        $root.AppendChild($notes)
    
        $Doc.AppendChild($root)
        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

    Participant
    Points: 27
    Rank: Member

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

  • #99901

    Participant
    Points: 0
    Rank: Member

    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)
        [void]$xml.AppendChild($Dec)
        $Root = $xml.CreateNode("element","Changes",$null)
        [void]$xml.AppendChild($Root)
        return ,$xml
    }

The topic ‘Unable to return XML from function’ is closed to new replies.