Click here to Skip to main content
13,006,530 members (60,689 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


1 bookmarked
Posted 6 Jan 2011

Formatting an XML string in Silverlight

, 7 Jan 2011
Rate this:
Please Sign up or sign in to vote.
If you have unformatted XML in a string and need to format it for visual presentation, e.g. for sending it to your UI, here's how to do it for Silverlight 4.0.
Silverlight doesn't have the XmlDocument class. You'd otherwise be able to do it as Ian Randell does here.

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

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;
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;
    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);
    if (xmlWriter != null)
  return stringBuilder.ToString();


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


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


About the Author

Paul Schwartzberg
Software Developer (Senior) Systemize Informatik GmbH
Denmark Denmark
Software Developer / Contractor

You may also be interested in...

Comments and Discussions

GeneralReason for my vote of 5 Great snippet, just what I needed. I... Pin
Diamonddrake19-Aug-11 14:51
memberDiamonddrake19-Aug-11 14:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170628.1 | Last Updated 7 Jan 2011
Article Copyright 2011 by Paul Schwartzberg
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid