tags:

views:

423

answers:

6

I want to output my InnerXml property for display in a web page. I would like to see indentation of the various tags. Is there an easy way to do this?

+1  A: 

You should be able to do this with code formatters. You would have to html encode the xml into the page first.

Google has a nice prettifyer that is capable of visualizing XML as well as several programming languages.

Basically, put your XML into a pre tag like this:

<pre class="prettyprint"> 
    &lt;link href="prettify.css" type="text/css" rel="stylesheet" /&gt;
    &lt;script type="text/javascript" src="prettify.js">&lt;/script&gt;
</pre>
Peter Lillevold
A: 

Use the XML Web Server Control to display the content of an xml document on a web page.

EDIT: You should pass the entire XmlDocument to the Document property of the XML Web Server Control to display it. You don't need to use the InnerXml property.

Rune Grimstad
A: 

If identation is your only cocern and if you can afford to launch xternall process, you can process xml file with HTML Tidy console tool (~100K).

The code is:

tidy --input-xml y --output-xhtml y --indent "1" $(FilePath)

Then you can display idented string on web page once you get rid of special chars.

It would be also easy to create recursive function that makes such output - simply iterate nodes starting from the root and enter next recursion step for child node, passing identation as a parameter to each new recursion call.

majkinetor
A: 

Check out the free Actipro CodeHighlighter for ASP.NET - it can neatly display XML and other formats.

Or are you more interested in actually formatting your XML? Then have a look at the XmlTextWriter - you can specify things like Format (indenting or not) and the indent level, and then write out your XML to e.g. a MemoryStream and read it back from there into a string for display.

Marc

marc_s
A: 

Use an XmlTextWriter with the XmlWriterSettings set up so that indentation is enabled. You can use a StringWriter as "temporary storage" if you want to write the resulting string onto screen.

Lucero
+2  A: 

Here's a little class that I put together some time ago to do exactly this.

It assumes that you're working with the XML in string format.

public static class FormatXML
{
    public static string FormatXMLString(string sUnformattedXML)
    {
        XmlDocument xd = new XmlDocument();
        xd.LoadXml(sUnformattedXML);
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        XmlTextWriter xtw = null;
        try
        {
            xtw = new XmlTextWriter(sw);
            xtw.Formatting = Formatting.Indented;
            xd.WriteTo(xtw);
        }
        finally
        {
            if(xtw!=null)
                xtw.Close();
        }
        return sb.ToString();
    }
}
CraigTP