读取XML文件作为数据集

本文关键字:数据集 文件 XML 读取 | 更新日期: 2023-09-27 17:54:52

我没有解析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>

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

读取XML文件作为数据集

如果你想使用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

另一个简单的方法是使用"ReadXml"内置方法。

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

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

参考