• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1104
  • Last Modified:

Show XML string in a div

Hello,

I have a XML which is kept in a string.
When I put it in a 'div' element, it looks like a long string instead of a formatted XML document.
Is it possible to show it as a formatted XML (with indentation etc.)

Thank you
0
Relegence
Asked:
Relegence
  • 14
  • 11
1 Solution
 
daveamourCommented:
You would need to replace windows type carriage returns with <br /> tags since that is what is used in html
0
 
daveamourCommented:
I just did a quick example of this.
I created the attached text file and then put a panel on my web page with a literal called Contents in there and code as follows:

Contents.Text = Server.HtmlEncode(System.IO.File.ReadAllText(@"P:\My Documents\Visual Studio 2008\Projects\EEGenericSolution\EEGenericWebApp\Data.txt")).Replace(Environment.NewLine, "<br />");

<?xml version="1.0" encoding="UTF-8"?>
<People>
	<Person id="1">
		<Name>Dave</Name>
		<Age>41</Age>
	</Person>
</People>

Open in new window

0
 
RelegenceAuthor Commented:
It would still not be indented as a XML.
Except for the carriage returns, inner tags are "tabbed" etc.
I guess what I need cannot be achieved
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
daveamourCommented:
Yes it can!
Replace also tabs with spaces
0
 
RelegenceAuthor Commented:
Just saw your second answer. I am going to try it now.
Will let you know if it worked

Thanks!
0
 
daveamourCommented:
Like this:

Contents.Text = Server.HtmlEncode(System.IO.File.ReadAllText(@"P:\My Documents\Visual Studio 2008\Projects\EEGenericSolution\EEGenericWebApp\Data.txt")).Replace(Environment.NewLine, "<br />").Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
0
 
RelegenceAuthor Commented:
I am afraid it didn't work for me.

I tried to change the following:

Replace(Environment.NewLine, "<br />")

to

Replace("\n", "<br />")

but that also didn't help
0
 
RelegenceAuthor Commented:
I think that the reason is that  my long XML string does not contain the "\t" or "\n" in it.
It is just a very long string
0
 
daveamourCommented:
It worked fine for me so lets try and fix yours.
Can you show me your xml and also where is it coming from?
Also how is this getting into the page - are you using a literal control for example?
 
0
 
daveamourCommented:
Oh ok - can you show me?
0
 
RelegenceAuthor Commented:
I get it by calling a WebService. What I get in return is a "StreamReader".

Below is the relevant code.


m_req = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["ServiceURL"]);
                m_req.Method = "POST";
                m_req.ContentType = "text;UTF-8";
                string postData = "Title=" + HttpUtility.UrlEncode(title) + "&Body=" + HttpUtility.UrlEncode(text);
                byte[] byteArr = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(postData);
                m_req.ContentLength = byteArr.Length;
 
                System.IO.Stream stream = m_req.GetRequestStream();
                stream.Write(byteArr, 0, byteArr.Length);
                stream.Close();
                myResponse = m_req.GetResponse();
 
                using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
                {
                    fullxml = sr.ReadToEnd();
                }
 
 
                myDiv.InnerText = fullxml;

Open in new window

0
 
daveamourCommented:
Ok so if you are getting a long string back without any tabs or carriage returns in then first push it through the attached method which will format it niceley and then replace the carriage returns and tabs as I mentioned earlier.  I just tested it and it does work.
       public static String PrettyPrint(String XML)
        {
            String Result = "";
 
            MemoryStream MS = new MemoryStream();
            XmlTextWriter W = new XmlTextWriter(MS, Encoding.Unicode);
            XmlDocument D = new XmlDocument();
 
            try
            {
                // Load the XmlDocument with the XML.
                D.LoadXml(XML);
 
                W.Formatting = Formatting.Indented;
 
                // Write the XML into a formatting XmlTextWriter
                D.WriteContentTo(W);
                W.Flush();
                MS.Flush();
 
                // Have to rewind the MemoryStream in order to read
                // its contents.
                MS.Position = 0;
 
                // Read MemoryStream contents into a StreamReader.
                StreamReader SR = new StreamReader(MS);
 
                // Extract the text from the StreamReader.
                String FormattedXML = SR.ReadToEnd();
 
                Result = FormattedXML;
            }
            catch (XmlException)
            {
            }
 
            MS.Close();
            W.Close();
 
            return Result;
        }

Open in new window

0
 
daveamourCommented:
PS you may want to do the replacing of tabs and carriage returns in the method I just posted then its all niceley encapsulated.
0
 
RelegenceAuthor Commented:
I am afraid I am still having some problems.
I see "<br />" in my output, instead of newLines
0
 
sybeCommented:
If you make it an iframe in stead of a div, it is quite easy: browser will do the formatting for you if the content-type is "text/xml".
0
 
daveamourCommented:
Ok sounds like you got your Server.HtmlEncode mised up.
Here is the complete code.  The PrettyPrint method wasn't quite right but does it all now - just copy and paste this and push your xml through it as I have done.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Xml;
using System.Text;
 
namespace EEGenericWebApp
{
    public partial class PrettyPrintXml : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Contents.Text = PrettyPrint(System.IO.File.ReadAllText(@"P:\My Documents\Visual Studio 2008\Projects\EEGenericSolution\EEGenericWebApp\Data.txt"));
        }
 
        public String PrettyPrint(String XML)
        {
            String Result = "";
 
            MemoryStream MS = new MemoryStream();
            XmlTextWriter W = new XmlTextWriter(MS, Encoding.Unicode);
            XmlDocument D = new XmlDocument();
 
            try
            {
                // Load the XmlDocument with the XML.
                D.LoadXml(XML);
 
                W.Formatting = Formatting.Indented;
                W.Indentation = 1;
                W.IndentChar = '\t';
 
                // Write the XML into a formatting XmlTextWriter
                D.WriteContentTo(W);
                W.Flush();
                MS.Flush();
 
                // Have to rewind the MemoryStream in order to read
                // its contents.
                MS.Position = 0;
 
                // Read MemoryStream contents into a StreamReader.
                StreamReader SR = new StreamReader(MS);
 
                // Extract the text from the StreamReader.
                String FormattedXML = SR.ReadToEnd();
 
                Result = FormattedXML;
            }
            catch (XmlException)
            {
            }
 
            MS.Close();
            W.Close();
 
            return Server.HtmlEncode(Result).Replace(Environment.NewLine, "<br />").Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
        }
    }
}

Open in new window

0
 
RelegenceAuthor Commented:
Works!
Thank you SO much!
0
 
daveamourCommented:
Your welcome
0
 
RelegenceAuthor Commented:
Just wanted to add the following:

Replace("\t", "      ") didn't work for me so I changed it to Replace("\t", " &nbsp;") which did
0
 
daveamourCommented:
Ok cool, I didn't say to put Replace("\t", "      ") though did I?
0
 
RelegenceAuthor Commented:
It was in the "PrettyPrint" function
0
 
daveamourCommented:
Nope it wasn't, check again!
0
 
RelegenceAuthor Commented:
return Server.HtmlEncode(Result).Replace(Environment.NewLine, "<br />").Replace("\t", "      ");

I copied that row from your reply which is marked as "Accepted solution"
0
 
daveamourCommented:
Nope that's not right - here look at the screenshot.
Screenshot.jpg
0
 
RelegenceAuthor Commented:
Below is what I saw.

Funny...

Thanks again anyway!
ea.jpg
0
 
daveamourCommented:
Ahh ok I see it is expert's exchange which has messed up!
My apologies :)
Dave
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 14
  • 11
Tackle projects and never again get stuck behind a technical roadblock.
Join Now