c# txt文本轉xml文本

來源:互聯網
上載者:User

現在很多軟體都是以xml檔案作為資料來源,而很多資料工具如pb等卻只能另存新檔txt、excel等格式,為此需要一工具能將txt文本轉換成xml檔案。google了一下,沒找到合適的,衝動之下用C#寫了一個txt文本轉xml格式文本的小程式,代碼如下。

       建立一個windows應用程式,命名該表單為FrmTxtXml,在該表單中添加:

       一個按鈕” toolStripOpen”,text為“開啟檔案”;

       一個按鈕” toolStripConvert”,text為“轉換”;

       一個按鈕” toolStripSaveas”,text為“另存新檔”;

       一個文字框” txtTXT”,顯示txt文本;

       一個文字框”txtXML5”,顯示xml格式文本;

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

            }

        }

    }

 

       運行程式,可將txt文本轉換為下述所示xml內容。

emp_no      emp_name  emp_xb      emp_bir

 11865       張三 1       1984/11/24 00:00:00

10     張三李       0       1963/7/16 00:00:00

100   張四李       0       1958/1/13 00:00:00

1000 張五李       1       1976/1/12 00:00:00

100001       張六李       0       1977/1/12 00:00:00

100002       張七李       1       1978/1/12 00:00:00

<?xml version="1.0" encoding="gbk"?>

<dataRoot>

<record>

<emp_no> 11865</emp_no>

<emp_name>張三</emp_name>

<emp_xb>1</emp_xb>

<emp_bir>1984/11/24 00:00:00</emp_bir>

</record>

<record>

<emp_no>10</emp_no>

<emp_name>張三李</emp_name>

<emp_xb>0</emp_xb>

<emp_bir>1963/7/16 00:00:00</emp_bir>

</record>

<record>

<emp_no>100</emp_no>

<emp_name>張四李</emp_name>

<emp_xb>0</emp_xb>

<emp_bir>1958/1/13 00:00:00</emp_bir>

</record>

<record>

<emp_no>1000</emp_no>

<emp_name>張五李</emp_name>

<emp_xb>1</emp_xb>

<emp_bir>1976/1/12 00:00:00</emp_bir>

</record>

<record>

<emp_no>100001</emp_no>

<emp_name>張六李</emp_name>

<emp_xb>0</emp_xb>

<emp_bir>1977/1/12 00:00:00</emp_bir>

</record>

<record>

<emp_no>100002</emp_no>

<emp_name>張七李</emp_name>

<emp_xb>1</emp_xb>

<emp_bir>1978/1/12 00:00:00</emp_bir>

</record>

</dataRoot>

 

原文:http://blog.csdn.net/chuangxin/article/details/5336756

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.