将数据从XML读取到2D数组中

时间:2015-11-27 06:26:06

标签: c# xml

我有一个xml文件。

data[0][0] = "ABC "
data[0][1] = "2005"
...
and so on

next movie.
data[1][0] = "cba"
data[1][1] = "2015"
...

我想为每部电影存储2D数组 像:

while (reader.Read())
{
    type = reader.NodeType;

    if (type == XmlNodeType.Element)
    {


            if (reader.Name == "title")
            {
                reader.Read();
                data[i, 0] = reader.Value;
            }

我该怎么办? 我正在尝试这种方式。

view.setEnabled(false);
myReqRecyclerView.setEnabled(false);

2 个答案:

答案 0 :(得分:1)

XML文件加载到DataTable的方法,只需将。xml文件的路径传递给它{/ p>

public static DataTable LoadDataTableFromXML(string Path)
{
      XmlDocument doc = new XmlDocument(); /* using System.Xml */
      doc.Load(Path);
      DataSet dataSet = new DataSet();
      dataSet.ReadXml(new StringReader(doc.InnerXml));
      return dataSet.Tables[0];
}

现在,该方法返回的DataTable包含.xml文件

中的数据
DataTable dtMovieDetails = LoadDataTableFromXML(Server.MapPath("xml file path"));

string[,] data = new string[dtMovieDetails.Rows.Count,dtMovieDetails.Columns.Count]; /*dtMovieDetails.Rows.Count represents number of Rows and dtMovieDetails.Columns.Count represents number of Columns in your xml file*/

int row = 0; /* row counter */
foreach (DataRow dataRow in dtMovieDetails.Rows)
{
   for(int col = 0; col < dataRow.ItemArray.Count(); col++) /*col is columns counter */
   { 
     data[row, col] = dataRow[col].ToString(); 
   }
   row++;
}

答案 1 :(得分:0)

        XmlReader xmlFile;
        xmlFile = XmlReader.Create("XMLPATH should be here", new   XmlReaderSettings());

        DataSet ds = new DataSet();
        ds.ReadXml(xmlFile);

        int row_count = ds.Tables[0].Rows.Count;
        int coloumn_count = ds.Tables[0].Columns.Count;
        string[,] data = new string[row_count,coloumn_count ];

        for (int i = 0; i < row_count; i++)
        {


            data[i, 0] = ds.Tables[0].Rows[i][0].ToString();
            data[i, 1] = ds.Tables[0].Rows[i][1].ToString();
            data[i, 2] = ds.Tables[0].Rows[i][2].ToString();
            data[i, 3] = ds.Tables[0].Rows[i][3].ToString();
            data[i, 4] = ds.Tables[0].Rows[i][4].ToString();
            data[i, 5] = ds.Tables[0].Rows[i][5].ToString();
            data[i, 6] = ds.Tables[0].Rows[i][6].ToString();
            data[i, 7] = ds.Tables[0].Rows[i][7].ToString();
            data[i, 8] = ds.Tables[0].Rows[i][8].ToString();
            data[i, 9] = ds.Tables[0].Rows[i][9].ToString();


        }