Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

Formatting unformatted XML string in LINQ – Code snippets

4.00/5 (2 votes)
18 Oct 2011CPOL 27.3K  
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:


C#
// Unformated XML string
string strUnformattedXML = 
  "<car><make>Nissan</make><model>Bluebird Sylphy" + 
  "</model><year>2007</year></car>";

// 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();
Console.WriteLine(strFormattedXML);

The output is:


XML
<car>
  <make>Nissan</make>
  <model>Bluebird Sylphy</model>
  <year>2007</year>
</car>

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


C#
XElement.Parse(strUnformattedXML).Save(@"C:\temp.xml");
Console.WriteLine(File.ReadAllText(@"C:\temp.xml"));

Then the output is:


XML
<?xml version="1.0" encoding="utf-8"?>
<car>
  <make>Nissan</make>
  <model>Bluebird Sylphy</model>
  <year>2007</year>
</car>

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


C#
using System;
using System.Xml.Linq;
using System.IO;

License

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