2013-01-19 42 views
7

我对解析XML文件不熟悉,并且将线图数据保存到xml文件,因此我做了一些研究。根据this文章,所有读取XML文件的方式中,DataSet是最快的。因为可能有大量的数据,所以我使用DataSet是有道理的。这里是我的图形文件的样子:将XML文件作为数据集读取

<?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解析器来获取我的图形数据吗?

回答

10

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

+0

InferSchema帮助我之前刚刚用空行导入 – user2648008

4

其他简单的方法是使用“ReadXml”内置方法。

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

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

Reference