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:
string strUnformattedXML =
"<car><make>Nissan</make><model>Bluebird Sylphy" +
"</model><year>2007</year></car>";
XElement xElement = XElement.Parse(strUnformattedXML);
string strFormattedXML = xElement.ToString();
Console.WriteLine(strFormattedXML);
The output is:
<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.
XElement.Parse(strUnformattedXML).Save(@"C:\temp.xml");
Console.WriteLine(File.ReadAllText(@"C:\temp.xml"));
Then the output is:
="1.0"="utf-8"
<car>
<make>Nissan</make>
<model>Bluebird Sylphy</model>
<year>2007</year>
</car>
Note: Make sure that the following namespaces are included beforehand:
using System;
using System.Xml.Linq;
using System.IO;
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.