Author Posts

April 23, 2018 at 11:43 am

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""

April 27, 2018 at 9:24 pm

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

April 27, 2018 at 9:42 pm

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
}