Sunday, December 6, 2009

Converting a comma seperated file into XML,using Linq To XML

In this post we aim to transform a text file into an XML fie.
The Text file will contain the following
information regarding a person entity: Fname,Lname,Age,Gender,Occupation

Kavita,Sharma,25,F,S/w eng
Nishant,Khandhadia,M,26,sr s/w eng
Mounin,Sharma,24,M,Businessman

Our goal is to parse the data in the text file and produce a hierarchy of XML as shown below:

var booksXml = new XElement("Persons",
from line in File.ReadAllLines("persons.txt")
let items = line.Split(',')
select new XElement("Person",
new XElement("FirstName", items[1]),
new XElement("LastName", items[1]),
new XElement("Age", items[2]),
new XElement("Gender", items[3]),
new XElement("Occupation", items[4])
);

No comments:

Post a Comment