Reputation: 2068
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* %>
Upvotes: 5
Views: 12891
Reputation: 5654
from https://stackoverflow.com/a/16605336/1874 , here is a simple 3 line solution:
var xml = "<root><A><B>0</B><C>0</C></A><D><E>0</E></D></root>";
XDocument doc = XDocument.Parse(xml);
Console.WriteLine (doc.ToString());
or inline as
XDocument.Parse(xmlstring).ToString()
place the result inside of (for example inspect the code blocks on this StackOverflow page):
<pre></pre>
Upvotes: 1
Reputation: 1425
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.
Upvotes: 3
Reputation: 30105
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
Upvotes: 7
Reputation: 28345
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.
Upvotes: 1
Reputation: 3415
try setting the content type to xml and add the xml header before your data, I use this simple prep function for my webservices, r is the Response object:
public void prepXml()
{
r.AddHeader("Content-Type", "text/xml");
r.Write("<?xml version=" + '"' + "1.0" + '"' + " encoding=" + '"' + "utf-8" + '"' + " ?>");
}
Upvotes: 0