将XML文件读取为DataSet

Bra*_*ler 9 c# xml performance dataset xml-parsing

我对解析XML文件缺乏经验,而且我将线图数据保存到xml文件中,所以我做了一些研究.根据这篇文章,在阅读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>
Run Code Online (Sandbox Code Playgroud)

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

小智 17

如果要使用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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


小智 5

其他简单方法是使用"ReadXml"内置方法.

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

注意:XML文件应该是有序的方式.

参考