i have a txt in following format:
1;name firstname;location;city;
2;name firstname;location;city;
.......
i would like to read this txt file and parse the output to xml like:
....
..........
is this in anyway possible ? should i parse the txt as a csv (i know there's a csvreader) ?
i don't have much experience working with files
any help or code snippets are appreciated
thanks alot in advance !
AlanPosted Oct 18, 2007, 9:39 AM
Try this:
using System;
using System.IO;
using System.Xml;
class Program
{
static void Main()
{
StreamReader sr = new StreamReader(@"C:\myfolder\txt\myfile.txt"); // or whatever
XmlTextWriter tw = new XmlTextWriter(@"C:\myfolder\xml\myfile.xml", null);
tw.Formatting = Formatting.Indented;
tw.WriteStartDocument();
tw.WriteStartElement("root");
string line = null;
string[] contents = null;
while ((line = sr.ReadLine()) != null)
{
contents = line.Split(';');
tw.WriteStartElement("user");
tw.WriteStartElement("id");
tw.WriteString(contents[0]);
tw.WriteEndElement();
tw.WriteStartElement("name_firstname");
tw.WriteString(contents[1]);
tw.WriteEndElement();
tw.WriteStartElement("location");
tw.WriteString(contents[2]);
tw.WriteEndElement();
tw.WriteStartElement("city");
tw.WriteString(contents[3]);
tw.WriteEndElement();
tw.WriteEndElement();
}
tw.WriteEndElement();
tw.Close();
sr.Close();
}
}