views:

504

answers:

3

C# Print Any Complete XML Document to Console?

Anyone have a snippet?

(Hides behind the cubicle...shit.)

+2  A: 

Are you just looking for:

Console.WriteLine(myXmlDoc.OuterXml); // Using System.Xml.XmlDocument
Greg D
thnx (Smiles)....now back to work...
abmv
Too bad this doesn't provide proper indentation.
phsr
Yeah, it's the quick and dirty version.
Greg D
Seen on another website: `myXmlDoc.Save(Console.Out);` This seems to add indentation.
Harvey
+2  A: 

I know this an old post but FWIW: Here's how you can "pretty print" your XML ...

public static String PrettyPrintXML(String sourceXML, Encoding encoding)
{
    using (MemoryStream memory = new MemoryStream())
    {
        using (XmlTextWriter xmlWriter = new XmlTextWriter(memory, encoding))
        {
            XmlDocument document = new XmlDocument();
            document.LoadXml(sourceXml);
            xmlWriter.Formatting = Formatting.Indented;
            xmlWriter.Indentation = 4;
            document.WriteContentTo(xmlWriter);
            xmlWriter.Flush();
            memory.Position = 0;
            using (StreamReader reader = new StreamReader(memory))
            {
                return reader.ReadToEnd();
            }
        }
    }
}
cmillens
+1  A: 

If you use an XDocument (in System.Xml.Linq) for your XML you can just call ToString() on it for an indented version of the XML within.

XDocument doc = XDocument.Load(Server.MapPath("~/Data.xml"));
Console.WriteLine(doc.ToString());

If you don't want it indented then use the overload of ToString() and pass in a SaveOptions enumeration:

Console.WriteLine(doc.ToString(SaveOptions.DisableFormatting));
Dan Diplo
by indented version, do you mean pretty xml?
Eric U.
By indented I mean that nested tags are indented so that it looks nicer and you can more easily see how the tags are nested. No other formatting is applied, though. If you look at http://msdn.microsoft.com/en-us/library/system.xml.linq.saveoptions.aspx it gives an example of the output.
Dan Diplo