我正在寻找一种帮助我快速读取XML DataBase导出文件的解决方案, 看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<database name="backup_db">
<table name="users">
<column name="username">user1</column>
<column name="password">pass1</column>
<column name="email">email1</column>
<column name="regdate">2015-01-22 23:31:59</column>
<column name="lastlogin">2016-12-11 01:56:24</column>
<column name="banned">0</column>
</table>
<table name="users">
...
</table>
...
200000 table rows
</database>
我创建了一个枚举所有元素并存储列值的解决方案,但执行时间很长。
var xd = new XmlDocument();
string path = Server.MapPath("~/App_Data/users.xml");
var fs = new FileStream(path, FileMode.Open);
xd.Load(fs);
var list = xd.GetElementsByTagName("table");
for (var i = 0; i < list.Count; i++)
{
...
}
fs.Close()
Whot让这项工作更快?
答案 0 :(得分:0)
试试以下内容。它只将数据添加为字符串,并且仅在列始终处于相同顺序(没有跳过的列)时才起作用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
if (reader.Name != "database")
{
reader.ReadToFollowing("database");
}
reader.MoveToFirstAttribute();
string databaseName = reader.Value;
DataSet ds = new DataSet(databaseName);
DataTable dt = null;
while (!reader.EOF)
{
if (reader.Name != "table")
{
reader.ReadToFollowing("table");
}
if (!reader.EOF)
{
XElement table = (XElement)XElement.ReadFrom(reader);
string tableName = (string)table.Attribute("name");
if (!ds.Tables.Contains(tableName))
{
dt = new DataTable(tableName);
ds.Tables.Add(dt);
dt.Columns.AddRange(table.Elements("column").Select(x => new DataColumn((string)x.Attribute("name"))).ToArray());
}
DataRow newRow = ds.Tables[tableName].Rows.Add();
newRow.ItemArray = table.Elements("column").Select(x => (string)x).ToArray();
}
}
}
}
}