如何从xml文件获取数据到datatable

时间:2016-04-07 06:33:32

标签: c# xml datatable readfile gridcontrol

我有一个像这样的xml文件。

<?xml version="1.0"?>
<Topic TopicName="FxhysS2vY64=">
  <Question>
    <QuestionID>HtjBCldKZg4=</QuestionID>
    <Details>Cg+MCbd9nTpJokauVrxHsyTqcvKCS8ePzHQCpUTVviWxAXriQVLy5w==</Details>
    <Description>x358GtJIXJI=</Description>
    <TrueOrFalse>D2zx2u5cwbo=</TrueOrFalse>
    <Points>W4VYuxBJeaY=</Points>
    <QuestionType>Fr1jj5tmWhMKNIKrHy18Rg==</QuestionType>
    <Caption>Cg+MCbd9nTpJokauVrxHsyTqcvKCS8ePAsNmzBfGJhg=</Caption>
    <TopicID>HtjBCldKZg4=</TopicID>
  </Question>
  <Question>
    <QuestionID>HtjBCldKZg4=</QuestionID>
    <Details>ccX0bHUdtg4ayF/7PfpFHUx9kPAGUBC5xOh1mw1b7d1g0lHifJ6AD49Niw1ipCPp</Details>
    <Description>x358GtJIXJI=</Description>
    <TrueOrFalse>JYEB3R1+ypE=</TrueOrFalse>
    <Points>W4VYuxBJeaY=</Points>
    <QuestionType>Fr1jj5tmWhMKNIKrHy18Rg==</QuestionType>
    <Caption>ccX0bHUdtg4ayF/7PfpFHUx9kPAGUBC5xOh1mw1b7d1g0lHifJ6AD49Niw1ipCPp</Caption>
    <TopicID>HtjBCldKZg4=</TopicID>
  </Question>
</Topic>

我想将它们放入数据表并在devexpress中的gridcontrol中显示 我的网格控制 enter image description here

那么,我该怎么做呢。非常感谢

2 个答案:

答案 0 :(得分:0)

尝试这个我认为它会帮助你

    public DataTable ReadXML(string file)
{
    DataTable table = new DataTable("XmlData");
    Stream stream = new  FileStream(file, FileMode.Open, FileAccess.Read);
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Power", typeof(int));
    table.Columns.Add("Location", typeof(string));
    table.ReadXml(stream);
    return table;
}

以下是完整的参考资料:

How to read XML into a DataTable?

答案 1 :(得分:0)

这是一个非常简单的方法,只需要很少的工作。您正在读取文件,因此无需使用流。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        const string FILENAME = @"c:\temp\test.xml";
        public Form1()
        {
            InitializeComponent();
            DataSet ds = new DataSet();
            ds.ReadXml(FILENAME);

            dataGridView1.DataSource = ds.Tables[1];
        }
    }
}