return sw.ToString();
This means that you did not show us the code you actually use: before that line is a different return statement.
return WP_XMLdoc;
and that's a correct return statement. The statement where according to your words the error is shown will never be executed.
sw.ToString()
returns a
string
. But the signature of the function says that the function returns an
XMLDocument
, hence the compiler tries to cast the string to XMLDocument, and that is not possible. To get an XMLDocument from a string, you can use the
LoadXml
function of XMLDocument.
But that's useless anyway, because you already have an XML document (
WP_XMLdoc
).
You try to accomplish something which you did not tell us - and all the code you showed is so weird because you got confused by not defining your requirements...