将XML文件读取为DataSet

时间:2013-01-19 07:34:15

标签: c# xml performance xml-parsing dataset

我对解析XML文件缺乏经验,而且我将线图数据保存到xml文件中,所以我做了一些研究。根据{{​​3}}文章,在阅读XML文件的所有方法中,DataSet是最快的。我使用DataSet是有道理的,因为可能存在大量数据。以下是我的图表文档的外观:

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<BreezyCalc>
    <Graph Version="3.0" Mode="static">
        <Range>
            <X Min="-20" Max="20" />
            <Y Min="-20" Max="20" />
        </Range>
        <Lines>
            <Line Name="MyLine1" R="0" G="255" B="0">
                <Point X="-17" Y="9" />
                <Point X="7" Y="-5" />
                <Point X="10" Y="4" />
                <Point X="-6" Y="2" />
            </Line>
            <Line Name="MyLine2" R="255" G="0" B="0">
                <Point X="-7" Y="3" />
                <Point X="8" Y="-1" />
                <Point X="-4" Y="-4" />
                <Point X="-1" Y="6" />
            </Line>
        </Lines>
    </Graph>
</BreezyCalc>

由于这些行中可能存在大量的点,因此我需要尽可能快地以尽可能少的资源获取数据。如果有比DataSet更快的方法,请赐教。否则,有人可以告诉我如何使用DataSet作为我的XML解析器获取图表数据吗?

2 个答案:

答案 0 :(得分:14)

如果要使用DataSet,则非常简单。

// Here your xml file
string xmlFile = "Data.xml";

DataSet dataSet = new DataSet();
dataSet.ReadXml(xmlFile, XmlReadMode.InferSchema);

// Then display informations to test
foreach (DataTable table in dataSet.Tables)
{
    Console.WriteLine(table);
    for (int i = 0; i < table.Columns.Count; ++i)
        Console.Write("\t" + table.Columns[i].ColumnName.Substring(0, Math.Min(6, table.Columns[i].ColumnName.Length)));
    Console.WriteLine();
    foreach (var row in table.AsEnumerable())
    {
        for (int i = 0; i < table.Columns.Count; ++i)
        {
            Console.Write("\t" + row[i]);
        }
        Console.WriteLine();
    }
}

如果你想要更快的东西,你可以尝试使用XmlReader,它逐行读取。但是开发起来有点困难。 你可以在这里看到它:http://msdn.microsoft.com/library/cc189056(v=vs.95).aspx

答案 1 :(得分:5)

其他简单的方法是使用&#34; ReadXml&#34;内置方法。

string filePath = "D:\\Self Practice\\Sol1\\Sol1\\Information.xml";
DataSet ds = new DataSet();
ds.ReadXml(filePath);

注意:XML文件应该是有序的。

Reference