Sean Kenny

Pretty Printing Xml or Json in HTML With C#

permalink

There are a few different ways to pretty print objects as html in C#. We have a requirement to pretty print what might be XML or Json. The following extension method does the trick:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static string PrettyPrint(this string serialisedInput)
{
  if (string.IsNullOrEmpty(input))
  {
    return input;
  }

  try
  {
    return XDocument.Parse(input).ToString();
  }
  catch (Exception) { }

  try
  {
    var t = JsonConvert.DeserializeObject<object>(input);
    return JsonConvert.SerializeObject(t, Formatting.Indented);
  }
  catch (Exception) { }

  return input;
}

In our case, we will have previously serialised the object into a datastore:

1
var serialisedItem = "{\"name\":\"sean\",\"roles\":[{\"roleName\":\"editor\"},{\"roleName\":\"admin\"}]}";

or for those of us unfortunate to work in 1998:

1
var serialisedItem = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Name>sean</Name><Roles><RoleName>editor</RoleName></Roles><Roles><RoleName>admin</RoleName></Roles>";

The Html/Razor syntax:

1
<pre>@serialisedItem.PrettyPrint()</pre>

Leads to (ta da!):

1
2
3
4
5
6
7
8
9
{
    "name" : "sean",
    "roles" : [{
          "roleName" : "editor"
        }, {
          "roleName" : "admin"
        }
    ]
}

or to:

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8" ?>
<Name>sean</Name>
<Roles>
    <RoleName>editor</RoleName>
</Roles>
<Roles>
    <RoleName>admin</RoleName>
</Roles>

Comments