将数组插入xml文件

时间:2019-02-23 10:20:38

标签: c# xml algorithm function text

有人知道吗,如何将二维int数组中的数据插入到已经创建的XML文件中? (我将使用XML文件作为GridView的源代码)

file.xml

<?xml version="1.0" encoding="utf-8" ?>
<file>

</file>

和我的数组[5] [5]

int[][] array = new int[5][5]{
{0 1 3 4 2},
{1 0 4 2 6},
{3 4 0 7 1}
{4 2 7 0 7},
{2 6 1 7 0}
};

任何人都可以帮助我弄清楚该怎么做?

1 个答案:

答案 0 :(得分:0)

最简单的方法是将数据放入数据表,然后使用WriteXml方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            DataTable dt = new DataTable("Array");
            dt.Columns.Add("Col_A", typeof(int));
            dt.Columns.Add("Col_B", typeof(int));
            dt.Columns.Add("Col_C", typeof(int));
            dt.Columns.Add("Col_D", typeof(int));
            dt.Columns.Add("Col_E", typeof(int));

            dt.Rows.Add(new object[] {0, 1, 3, 4, 2});
            dt.Rows.Add(new object[] {1, 0, 4, 2, 6});
            dt.Rows.Add(new object[] {3, 4, 0, 7, 1});
            dt.Rows.Add(new object[] {4, 2, 7, 0, 7});
            dt.Rows.Add(new object[] {2, 6, 1, 7, 0});

            dt.WriteXml(FILENAME, XmlWriteMode.WriteSchema);

        }
    }
}