加载数据表时过滤xml文件

时间:2013-02-13 13:46:04

标签: c# .net xml filter dataset

            DataSet ds = new DataSet();
            DataTable dataTable = new DataTable();
            ds.ReadXml("File.xml");
            dataTable = ds.Tables[0];
            LoadListView(dataTable);  

  <?xml version="1.0"?>
    <Book>
       <note1>
        <to>Tove</to>
        <from>Jani</from>
        <heading>Reminder</heading>
        <body>Don't forget me this weekend!</body>
      </note1>
    </Book>

我正在读取数据集中的整个xml文件,然后将所有记录显示为Listview。 但是当我将所有数据加载到listview时内存消耗更多。 Datatable占用了我机器的所有内存,并且在某些时候偏离了我的异常内存Exception.Is可以在过滤后加载数据表。 上面是我的xml文件,有多个节点我只需加载具有XmlElement的数据表中的那些节点,从&#39; j&#39;开始。 我会很感激你的答案。 我不想使用XMlDocument或Xpathquery或LINQ to XML

1 个答案:

答案 0 :(得分:2)

这是基于您知道XML文件结构的非常弱的假设(即格式具有稳定,统一的结构)。此外,我不知道这会给你的情况带来什么样的性能提升(因为更多的对象被实例化)。但是让我们试一试。

class Program
{
    static void Main(string[] args)
    {
        List<string> list = new List<string>();
        List<int> positions = new List<int>();
        bool checkNext = false;
        int position = -1;

        DataTable dataTable = new DataTable();
        dataTable.Columns.Add("to");
        dataTable.Columns.Add("from");
        dataTable.Columns.Add("heading");
        dataTable.Columns.Add("body");

        var rs = new XmlReaderSettings();
        rs.IgnoreWhitespace = true;

        using (var reader = XmlReader.Create(File.OpenRead("data.xml"), rs))
        {
            while (reader.Read())
            {
                if (reader.Name == "")
                {
                    list.Add(reader.Value);
                    position++;
                }
                if (checkNext)
                {
                    // TODO: apply your filter
                    if (reader.Value.ToLower().StartsWith("j"))
                    {
                        positions.Add(position);
                    }
                }
                if (reader.Name == "from")
                {
                    checkNext = !checkNext;
                }
            }
        }

        foreach (int match in positions)
        {
            dataTable.Rows.Add(
                list[match - 1],
                list[match],
                list[match + 1],
                list[match + 2]);
        }

        //LoadListView(dataTable);  
    }
}
相关问题