Redirect (System.Xml.XmlDocument).Save() to a variable

by Ritmo2k at 2013-02-14 10:16:54

I need to store the textual representation of a System.Xml.XmlDocument object into a variable, I see you can redirect the save() to the console, but how about a string variable?

Thanks!
by MattG at 2013-02-14 16:52:03
Here’s an example of what I think you’re looking for:
$Site = Invoke-WebRequest Recent Questions - Stack Overflow
$XMLFeed = [xml] $Site.Content
$StringWriter = New-Object IO.StringWriter
$XMLFeed.Save($StringWriter)
$RawOutput = $StringWriter.ToString()
The Save method has the following overloaded definitions:
OverloadDefinitions
-------------------
void Save(string filename)
void Save(System.IO.Stream outStream)
void Save(System.IO.TextWriter writer)
void Save(System.Xml.XmlWriter w)
I chose System.IO.StringWriter which inherits from System.IO.TextWriter whose ToString method outputs the raw XML. This is the best approach I could come up with.

I hope this answers your question.
by Ritmo2k at 2013-02-14 17:07:00
Ugh, much simpler than I finally arrived at! How do you enumerate the overload defs, I presume you have to hit the msdn docs on this class. I was trying to use get-member -force…

Thanks a ton!
by MattG at 2013-02-14 17:28:28
My pleasure! You can see the overloaded definitions in powershell by typing any method name without parentheses. Some examples:
$XMLFeed.Save
'hi'.Replace
(3).Equals
by Ritmo2k at 2013-02-14 17:42:21
Thats pretty awesome, I am spoiled with the iPython console and a good IDE like PyCharm when working in Python.

Didn’t know that one existed!

Cheers!