我打算將文本文件轉換爲XML。我使用下面的代碼。但它會在第12行中產生錯誤。任何人都可以更正代碼。錯誤在這一行。將文本文件轉換爲XML文件
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");
}
謝謝你的幫助,你可以提供必要的代碼,這樣我就可以清楚地瞭解它 – Kasun 2010-06-19 06:24:58