Monday, October 10, 2011

Show an object instance as an xnl on your page

This sample code demonstrates how to show an instance of an object in XML format on a page. It encodes the xml serialized string and dumps it as a code into a placeholder.

    public void ShowXmlObject<T>( T instance)
    {
        var ms = new MemoryStream();
        System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(ms, Encoding.Unicode);
        var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
        serializer.Serialize(writer, instance);
        writer.Flush();
        ms.Position = 0;
        var reader = new StreamReader(ms);
        LogCode(HttpUtility.HtmlEncode(IndentXml(reader.ReadToEnd())));
    }
    public string IndentXml(string xml)
    {
        var p = xml.LastIndexOf("?>");
        if (p > 0)
            xml = xml.Substring(p + 2);
        var doc = new System.Xml.XmlDocument();
        doc.LoadXml(xml);

        var settings = new System.Xml.XmlWriterSettings();
        settings.Indent = true;
        settings.IndentChars = "  ";
        settings.NewLineChars = "\r\n";
        settings.NewLineHandling = System.Xml.NewLineHandling.None;
        var  sbOutput = new StringBuilder();
        var writer = System.Xml.XmlWriter.Create(sbOutput, settings);
        doc.Save(writer);
        writer.Close();
        return sbOutput.ToString();
    } 
    public void LogCode(string message)
    {
        placeResult.Controls.Add(new Literal() { Text = "<pre><code>" + message + "</code></pre>" });
    }