Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Display Formatted XML

I have xml data that I am returning to my view. I am putting it in a textarea, but this displays it unformatted. How can I format the xml for display in my view?

I will be displaying the xml in only part of the page, so I can't let IE display it. I want it to be in standard xml indented format.

like image 303
Joe Avatar asked Jan 27 '10 17:01

Joe


People also ask

How do I view formatted XML files?

Go to http://www.xmlviewer.org/ in your computer's web browser. This viewer allows you to upload an XML file to view its code, as well as choose different viewing formats.

How do I make an XML file readable?

XML files are encoded in plaintext, so you can open them in any text editor and be able to clearly read it. Right-click the XML file and select "Open With." This will display a list of programs to open the file in. Select "Notepad" (Windows) or "TextEdit" (Mac).

How do I display an XML file in a table?

To bind an XML data to an HTML table, add the datasrc (data source) attribute to the table element, then add the datafld (data field) attributes to any other inline eg. <div>, <span> or <input> tags between the <td> elements.

How do I display and in XML?

Use &amp; in place of & . Just in case anyone reaches this question the same i did, there is the list of escape characters in . xml files and how to escape them: ibm.com/support/knowledgecenter/en/SSEQTP_liberty/…


3 Answers

If, by "formatting", you mean indented then you can load it into XmlDocument and write it into an XmlWriter initialized with an XmlWriterSettings that has Indent set to true.

private string FormatXml(string input)
{
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(input);

    using (StringWriter buffer = new StringWriter())
    {
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;

        using (XmlWriter writer = XmlWriter.Create(buffer, settings))
        {
            doc.WriteTo( writer );

            writer.Flush();
        }

        buffer.Flush();

        return buffer.ToString();
    }
}
like image 98
Richard Szalay Avatar answered Sep 23 '22 02:09

Richard Szalay


Simply load the XML into an XElement, then use XElement.ToString().

like image 43
John Saunders Avatar answered Sep 24 '22 02:09

John Saunders


You can use an XSLT to convert your XML into XHTML and then display that.

like image 31
Jeff Yates Avatar answered Sep 20 '22 02:09

Jeff Yates