Hi all,
I going to convert text file to XML. I use the following code. But it generate error in line 12. Can anyone correct the code. Error is in this line.
writer.WriteString(lines[0].TrimEnd().Split(ca, 2)[1]); ------ "Index was outside the bounds of the array."
private void button1_Click(object sender, EventArgs e) {
string[] lines = File.ReadAllLines("ex3.txt");
char[] ca = new char[] { '\n' };
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();
MessageBox.Show("Success");
}