public partial class FrmTxtXml :Form { String txtContent = String.Empty; // public FrmTxtXml() { InitializeComponent(); } //開啟txt檔案 private void toolStripOpen_Click(object sender, EventArgs e) { using (OpenFileDialog fileDialog =new OpenFileDialog()) { fileDialog.Filter = "文字檔(*.txt)|*.txt"; if (fileDialog.ShowDialog() ==DialogResult.OK) { String fileName = fileDialog.FileName; if (!String.IsNullOrEmpty(fileName)) { using (StreamReader st =new StreamReader(fileName, System.Text.Encoding.GetEncoding("GBK"))) { txtContent = st.ReadToEnd(); //讀取txt檔案到txtTXT文字框 this.txtTXT.Text = txtContent; st.Close(); } } } } } //將txt檔案內容轉換成xml格式內容 private void toolStripConvert_Click(object sender,EventArgs e) { try { //將txt內容分解為行數組 String[] lines = this.txtTXT.Text.Split(new string[] { "/r/n" }, StringSplitOptions.None); String[] heads = null; if (lines != null && lines.Length > 0) { //讀取第一行資料,該行資料為xml檔案的節點描述資料 heads = lines[0].Split(newstring[] { "/t" },StringSplitOptions.None); //MessageBox.Show(heads.Length.ToString() + " " + heads[0]); } // StringBuilder sb =new StringBuilder(); sb.Append("<?xml version=/"1.0/" encoding=/"gbk/"?>").Append(Environment.NewLine).Append("<dataRoot>").Append(Environment.NewLine); //產生xml節點 for (int i = 1; i < lines.Length; i++) { if (lines[i] ==null || lines[i].Trim().Length < 1) continue; String[] info = lines[i].Split(newstring[] { "/t" },StringSplitOptions.None); sb.Append(createNode(heads, info)); } sb.Append("</dataRoot>"); this.txtXML.Text = sb.ToString(); } catch (Exception exp) { MessageBox.Show(exp.Message); } } //產生xml節點 private String createNode(String[] head, String[] info) { StringBuilder sb = new StringBuilder(); sb.Append("<record>").Append(Environment.NewLine); for (int i = 0; i < head.Length; i++) { sb.Append("<" + head[i] +">" + info[i] + "</" + head[i] +">").Append(Environment.NewLine); } sb.Append("</record>").Append(Environment.NewLine); return sb.ToString(); } //將txtXML文字框內容另存新檔xml檔案 private void toolStripSaveas_Click(object sender, EventArgs e) { try { String fileName =""; using (SaveFileDialog fileDialog =new SaveFileDialog()) { fileDialog.Filter = "XML資料檔案(*.xml)|*.xml"; if (fileDialog.ShowDialog() ==DialogResult.OK) { fileName = fileDialog.FileName; if (!String.IsNullOrEmpty(fileName)) { FileStream fs =new FileStream(fileName,FileMode.Create); //獲得位元組數組 byte[] data = System.Text.Encoding.GetEncoding("GBK").GetBytes(this.txtXML.Text); //開始寫入 fs.Write(data, 0, data.Length); //清空緩衝區、關閉流 fs.Flush(); fs.Close(); } } } MessageBox.Show(String.Format("檔案成功儲存到{0}", fileName)); } catch (Exception exp) { MessageBox.Show(exp.Message); } } } |