从XML </t>获取过滤的List <t>

时间:2011-12-01 12:58:39

标签: c# xml linq-to-xml

我正在使用以下代码从xml文件中获取List -

    public static List<T> GetListFromXml<T>(string filePath)
    {
        using (TextReader reader = new StreamReader(filePath))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
            return (List<T>) serializer.Deserialize(reader);
        }
    }

但是,我还需要一种过滤记录的方法,我可以通过 -
过滤列表 - 不。从xml文件中获取的记录数 - 按特定节点值过滤
因此上述方法的签名将更改为 -

    public static List<T> GetListFromXml<T>(string filePath, 
                                            int listCount, 
                                            string filterbyNode, 
                                            string filterByValue);

如果我可以直接从XML文件过滤,或者我应该从返回的列表中过滤,请指导我吗?


P.S。

上面提到的xml文件也是使用 -

从代码创建的
    public static void WriteListToXml<T>(List<T> list, string filePath)
    {
        using (TextWriter writer = new StreamWriter(filePath))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
            serializer.Serialize(writer, list);
        }
    }

为什么我将从数据库返回的自定义集合保存到xml文件 - 因为我想一次只处理一批记录。

和XML文件片段(从上面的代码生成) -

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfClassifiedLocation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <CLocation>
    <CId>5726</CId>
    <Long>0</Long>
    <Lat>0</Lat>
    <Postcode>ZZ1 5ZZ</Postcode>
    <Street />
    <Town />
  </CLocation>
  <CLocation>
    <CId>5736</CId>
    <Long>0</Long>
    <Lat>0</Lat>
    <Postcode>ZZ1 5ZZ</Postcode>
    <Street />
    <Town />
  </CLocation>
</ArrayOfClassifiedLocation>

2 个答案:

答案 0 :(得分:2)

如果您有权访问.net&gt; = 3.5,则应考虑使用Linq to Xml

答案 1 :(得分:1)

下面是考虑cid paremeter过滤器的LINQ-to-XML查询示例。如果在cidFilter中放入空字符串,则查询将返回所有条目:

// you can use Parse() method:
// XDocument loaded = XDocument.Parse(xmlString);
XDocument loaded = XDocument.Load("c:\\temp\\testxl.xml");

// return only entry fith CID == 5726
string cidFilter = "5726";
var filteredItems =
loaded.Descendants("CLocation")
    .Select((w, i) =>
            new
                {
                    Index = i,
                    CID = w.Descendants("CId").FirstOrDefault().Value,
                    PostCode = w.Descendants("Postcode").FirstOrDefault().Value
                })
    .Where(item => String.IsNullOrEmpty(cidFilter) || item.CID == cidFilter)
    .ToList();

int itemsCount = filteredItems.Count();
相关问题