Click here to Skip to main content
12,823,058 members (46,627 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


1 bookmarked
Posted 5 Oct 2011

Formatting unformatted XML string in LINQ – Code snippets

, 18 Oct 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
How to format unformatted XML string easily with LINQ.

This is very basic to most, but I thought of sharing this with those who are looking for a simple way to format unformatted XML strings.

With the use of the System.Xml.Linq namespace, you can represent the XML element and its string representation as follows:

// Unformated XML string
string strUnformattedXML = 
  "<car><make>Nissan</make><model>Bluebird Sylphy" + 

// Load the XElement from a string that contains XML representation
XElement xElement = XElement.Parse(strUnformattedXML);

// Returns the intended XML and display
string strFormattedXML = xElement.ToString();

The output is:

  <model>Bluebird Sylphy</model>

However, the XML declaration is not returned by ToString(). Save the file and open.


Then the output is:

<?xml version="1.0" encoding="utf-8"?>
  <model>Bluebird Sylphy</model>

Note: Make sure that the following namespaces are included beforehand:

using System;
using System.Xml.Linq;
using System.IO;


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


About the Author

Software Developer (Senior)
Sri Lanka Sri Lanka
I graduated with a BSc honours degree in Computer Science & Engineering from Peradeniya University. Currently work as a Senior Software Engineer in Colombo.

I started my career with programming in Java, which I happen to master at later stages of my career. Then later stages I move with Microsoft technologies like C/C++, .Net, SQL Servers and Web 2.0 technologies. Currently re-learning PHP.

Now I'm spending my time with reading for my masters in Artificial Intelligence.

You may also be interested in...

Comments and Discussions

QuestionWrong output snippet? Pin
John Whitmire18-Oct-11 9:49
memberJohn Whitmire18-Oct-11 9:49 
AnswerRe: Wrong output snippet? Pin
CodingLover18-Oct-11 18:52
memberCodingLover18-Oct-11 18:52 

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.170308.1 | Last Updated 18 Oct 2011
Article Copyright 2011 by CodingLover
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid