Lucas
Lucas

Reputation: 167

Convert Text.txt file .xml format

I try to convert text file to xml file using following code. But i get error in line 12. Could any one correct it and give me the correct answer.

private void button1_Click(object sender, EventArgs e)
{

    string[] lines = File.ReadAllLines("ex3.txt");
    char[] ca = new char[] { '~' };
    using (XmlTextWriter writer = new XmlTextWriter("ex3.xml", null))
    {
        writer.Formatting = Formatting.Indented;
        writer.WriteStartDocument();
        writer.WriteStartElement("Root");
        writer.WriteStartElement("Header");
        writer.WriteStartElement("H1");
        writer.WriteString(lines[0].TrimEnd().Split(ca, 2)[1]);
        writer.WriteEndElement();
        writer.WriteStartElement("H2");
        writer.WriteString(lines[1].TrimEnd().Split(ca, 2)[1]);
        writer.WriteEndElement();
        writer.WriteEndElement();
        writer.WriteStartElement("Details");
        for (int i = 2; i < lines.Length - 2; i++)
        {
            writer.WriteStartElement("D" + (i - 1).ToString());
            writer.WriteString(lines[i].TrimEnd().Split(ca, 2)[1]);
            writer.WriteEndElement();
        }
        writer.WriteEndElement();
        writer.WriteStartElement("Footer");
        writer.WriteStartElement("F1");
        writer.WriteString(lines[lines.Length - 2].TrimEnd().Split(ca, 2)[1]);
        writer.WriteEndElement();
        writer.WriteStartElement("F2");
        writer.WriteString(lines[lines.Length - 1].TrimEnd().Split(ca, 2)[1]);
        writer.WriteEndElement();
        writer.WriteEndElement();
        writer.WriteEndDocument();
    }
}

Thanks

This is the Error

System.IndexOutOfRangeException was unhandled Message="Index was outside the bounds of the array." Source="txtxml" StackTrace: at txtxml.Form1.button1_Click(Object sender, EventArgs e) in C:\Documents and Settings\Crusaders\My Documents\Visual Studio 2005\Projects\txtxml\txtxml\Form1.cs:line 31 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at txtxml.Program.Main() in C:\Documents and Settings\Crusaders\My Documents\Visual Studio 2005\Projects\txtxml\txtxml\Program.cs:line 17 at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()

Upvotes: 0

Views: 2919

Answers (2)

apoorv020
apoorv020

Reputation: 5650

@LBushkin raises one of the main problems with the code.
The second problem is that it assumes that each line contains atleast one '~'(you keep accessing .split(ca,2)[1]) , which does not seem to be the case in the sample txt file you posted. I suggest replacing all code of the form :

writer.WriteString(lines[0].TrimEnd().Split(ca, 2)[1]);

string[] splitLine = lines[0].TrimEnd().Split(ca,2);
if(splitLine.Length >1)
  writer.WriteString(splitLine[1]);

Upvotes: 0

LBushkin
LBushkin

Reputation: 131726

The code assumes that there exist at least four lines of text in the file. Are you sure this is the case?

I would suggest you write your code to first assert that the lines array actually contains as many lines as you expect. It's entirely possible that the file does not - or that the line breaks are non-standard and therefore not recognized by ReadAllLines().

string[] lines = File.ReadAllLines("ex3.txt"); 
char[] ca = new char[] { '~' }; 
if( lines.Length < 4 ) { /* decide how to handle this... */ }

//... your code

As a general rule, when parsing or splitting the contents of a file that you expect to have a certain format, you should write your code in a way that asserts your expectations. Otherwise, it can become quite difficult to diagnose what occurred when things go wrong.

Another place in your code you may want to re-examine, are lines like:

writer.WriteString(lines[0].TrimEnd().Split(ca, 2)[1]); 

Here, again, you assume that the line has a certain structure, and then you access the second index in the result using the indexing operator [] - which could also be a potential source of the error.

Upvotes: 2

Related Questions