Link to home
Start Free TrialLog in
Avatar of Relegence
RelegenceFlag for Israel

asked on

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
Avatar of daveamour
daveamour
Flag of United Kingdom of Great Britain and Northern Ireland image

You would need to replace windows type carriage returns with <br /> tags since that is what is used in html
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

Avatar of Relegence

ASKER

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
Yes it can!
Replace also tabs with spaces
Just saw your second answer. I am going to try it now.
Will let you know if it worked

Thanks!
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;");
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
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
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?
 
Oh ok - can you show me?
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

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

PS you may want to do the replacing of tabs and carriage returns in the method I just posted then its all niceley encapsulated.
I am afraid I am still having some problems.
I see "<br />" in my output, instead of newLines
Avatar of sybe
sybe

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".
ASKER CERTIFIED SOLUTION
Avatar of daveamour
daveamour
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Works!
Thank you SO much!
Your welcome
Just wanted to add the following:

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

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

Funny...

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