Click here to Skip to main content
Click here to Skip to main content

Formatting an Xml string in Silverlight

, 12 Jul 2011
Rate this:
Please Sign up or sign in to vote.
Formatting XML in a string for visual presentation.

Introduction

If you have unformatted XML in a string and need to format it for visual presentation, e.g., for sending it to your UI text display control, here's how to do it in Silverlight 4.0.

Silverlight doesn't have the XmlDocument class. You'd otherwise be able to do it as Ian Randell does in his article.

Instead, Silverlight currently (Jan 2011) offers the XDocument and XmlWriter classes. So you'd do it with these two classes as shown below:

Using the code

Just call the XmlFormat method below and display the result, i.e., with indenting and line breaks, in your UI control.

using System.Xml;
using System.Xml.Linq;
using System.Text;
/// <summary>
/// Formats unformatted xml string input.
/// </summary>
/// <param name="stringXml">unformatted xml string</param>
/// <returns>Formatted xml string based on <paramref name="stringXml" /></returns>
private string FormatXml(string stringXml)
{
    StringReader stringReader = new StringReader(stringXml);
    //XDocument represents an XML Document,
    //allowing in memory processing of it (primarily via Linq).
    XDocument xDoc = XDocument.Load(stringReader); 
    var stringBuilder = new StringBuilder();
    XmlWriter xmlWriter = null;
    try
    {
        var settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.ConformanceLevel = ConformanceLevel.Auto;
        settings.IndentChars = " ";
        settings.OmitXmlDeclaration = true;
        //The XDocument can write to an XmlWriter.
        //The writer formats the well-formed xml.
        //If not well-formed no formating will occur.
        xmlWriter = XmlWriter.Create(stringBuilder, settings);// xd.cre(sw);
        xDoc.WriteTo(xmlWriter);
    }
    finally
    {
        if (xmlWriter != null)
            xmlWriter.Close();
    }
    return stringBuilder.ToString();
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140709.1 | Last Updated 12 Jul 2011
Article Copyright 2011 by Paul Schwartzberg
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid