Thursday, November 10, 2011

Convert XmlText to HtmlText

I have been using Xml streams for quite some time. When I use them in an ASP.Net page, using SOAP or Ajax calls, I sometimes want to see what I send and what I recieve from the server. Showing them on the page was always a bit of tweak. This ample code demonstrates a very simple tweek. It provides a label that can show the xml Text (as its content or Text property) on the page, by rendering the simpel characters.
When the control is compiled I can use it as one of the two ways:

<panahyAjax:XmlLabel runat="server" ID="xmlLabel">
<is just="one">sample</is>


XmlLabel label = new XmlLabel();
var file = File.OpenText("Sample.xml");
label.Text = file.ReadToEnd();

And the code is as folllows:

public class XmlLabel : Label
 public static string ConvertXmlTextToHtmlText(string inputText)
  // Replace all start and end tags.
  string startPattern = @"<([^>]+)>";
  var regEx = new Regex(startPattern);
  string outputText = regEx.Replace(inputText, "&lt;<b>$1&gt;</b>");
  outputText = outputText.Replace(
" ", "&nbsp;");
  outputText = outputText.Replace(
"\r\n", "<br />");
  return outputText;

 protected override void RenderContents(HtmlTextWriter output)
  string xmlText = XmlLabel.ConvertXmlTextToHtmlText(Text);