Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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* %>
like image 797
tehdoommarine Avatar asked Feb 06 '12 16:02

tehdoommarine


3 Answers

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

like image 198
Samich Avatar answered Nov 01 '22 09:11

Samich


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.

like image 27
Gavin Coates Avatar answered Nov 01 '22 09:11

Gavin Coates


All your problems are because of all browsers are truncating the spaces in xml.
Try to use &nbsp; 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.

like image 29
VMAtm Avatar answered Nov 01 '22 10:11

VMAtm