tags:

views:

104

answers:

2

Hi,

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()

+1  A: 

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.

LBushkin
But can you provide me the correct code
Kasun
@Kasun, come on, this is madness, people don't have magic spheres and cannot guess what your function is supposed to do. Provide sample input and sample output.
Darin Dimitrov
@Kasun - only you know what the requirements of your application are, what the format of the input data should be, or what you could or should do if the expectations or preconditions are not met. **No one else can tell you what to do.** As I indicate in my answer, the problem is most likely that one of these expectations/assumptions is violated *by the input data*. You should write your code to verify the preconditions, and then take appropriate action if they are not met - perhaps notifying the user.
LBushkin
I only need to read text file and convert it to XML file.Text file look as follows: sdsdxsxcxcsdfsdfsdfsdfssdfsdf234234!@#$XML file : Is the same as text file
Kasun
The example above doesn't contain any `~` characters. DO these exist in the file - because your code specifically expects, on lines like: `writer.WriteString(lines[0].TrimEnd().Split(ca, 2)[1]);`
LBushkin
@Kasun, do you speak english?
Darin Dimitrov
Yep, But if you cannot provide me the correct answer, I dont have time to listen to you
Kasun
I can provide an answer but in order to provide a correct answer you need to ask a question first don't you? Don't you understand that until you provide an example input text file and expected output XML file you won't get any help? Is this so difficult to understand?
Darin Dimitrov
I tell you the question many times. If you cannot read and understand no point of it. Thanx for the help..
Kasun
No you didn't ask the question. You only pasted some source code and say a `I try to convert text file to xml file`. Do you know that there's an infinity of possible text files and XML files? You didn't say what you expect as an output so that people can try to reproduce the error on their machines and help you. How do you expect someone to help you if he is not able to run your code? Believe me, people here are really willing to help fellow developers. But make an effort and update your original question by providing sample input and output.
Darin Dimitrov
Don't worry. I got the correct answer.Only need to put ~ beginning of each line of the text file :)
Kasun
Your code is the last thing I worry about at the moment :-)
Darin Dimitrov
I don't care.....
Kasun
Me neither.....
Darin Dimitrov
@LBushkin, sorry about you being notified about all this crap :-)
Darin Dimitrov
Ahh... Did u got how to answer question. Plz refer @LBushkin answer for my question
Kasun
A: 

@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]);
apoorv020
This works.... Thanx buddy
Kasun