how to display human readable xml in an asp.net mvc view page

11,544

Solution 1

I was doing it in this way:

protected string FormatXml(XmlNode xmlNode)
{        
    StringBuilder builder = new StringBuilder();

    // We will use stringWriter to push the formated xml into our StringBuilder bob.
    using (StringWriter stringWriter = new StringWriter(builder))
    {
        // We will use the Formatting of our xmlTextWriter to provide our indentation.
        using (XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter))
        {
            xmlTextWriter.Formatting = Formatting.Indented;
            xmlNode.WriteTo(xmlTextWriter);
        }
    }

    return builder.ToString();
}

http://forums.asp.net/t/1145533.aspx/1

Solution 2

The problem is you are outputting text, which will then be interpreted by the browser in the default way that text is handled - it doesnt know that it is XML.

What you need is a library to correctly format the text using standard XML rules.

You could try Google Prettify - which is a Javascript library to format code (it supports XML as well as many other programming languages). There is also a .NET based formatter that you could use, I think it was written by Stack Overflow and open sourced - but I cannot find it right now.

Solution 3

All your problems are because of all browsers are truncating the spaces in xml.
Try to use   to draw intends or simply add the declaration of the xml to start of the page:

<?xml version="1.0" ?>
<this>
  <is sample = "attribute">
    <xml>
       <power> !!! </power>
    </xml>
    <oh>
       <yeah>
       </yeah>
    <oh>
  </is>
</this>

All modern browsers will handle this correctly.

Share:
11,544
tehdoommarine
Author by

tehdoommarine

If you don't want an upvote when you answer a question I have (for Unsung), please put a :) somewhere in your answer. Otherwise, I upvote all accepted answers.

Updated on June 12, 2022

Comments

  • tehdoommarine
    tehdoommarine almost 2 years

    I have a string in a ASP.NET MVC details page with the value of

    <this><is sample = "attribute"><xml><power>!!!</power></xml><oh><yeah></yeah></oh></is></this>.
    

    I want it to display as follows:

    <this>
      <is sample = "attribute">
        <xml>
           <power> !!! </power>
        </xml>
        <oh>
           <yeah>
           </yeah>
        <oh>
      </is>
    </this>
    

    Things I have tried:

    1: How to Display Formatted XML - best answer and richards answer

    2: xmlwriter.writeraw();

    3: basic linq-to-xml (i'm not very good with this)

    EDIT: I am displaying the string as follows and was wondering if this may have something to do with it:

    <%: *formatted string goes here* %>