查询XML文档

查询XML文档
    LINQ to XML类提供属性和方法,返回可查询的类的对象集合。 
    将XML对象作为LINQ查询对象: 
     ....... 
    XDocument customers = XDocument.Load(xmlFileName); 
    var queryResult = from c in customers.Elements() select c.Name;  
    使用查询成员 
        1)Element():返回文档 或 片段中的第一个元素。文档的话就返回根元素;
        2)Descendants():返回文档 或 片段中的所有子元素(所有级别);
            例:queryResults = from c in customers.Descendants() select c.Name;
                 foreach (var item in queryResults.Distinct()//筛选出不同的元素 
                 Descendants(string)重载:
                 queryResults = from c in customers.Desendants("customer") select c;  //查询指定名称的子元素,返回所有customer元素。 
        3)Ancestors():返回比源元素级别高的一组元素; 
        4)Attribute():返回当前选中元素的所有属性; 
            例:queryResults = from c in customers.Descendants("customer").Attributes() select c;//返回customers中所有customer元素的属性值 
                      显示c的话是:ID City Company ....ID City Company............. 
                 Attribute(sting)重载:
                 queryResults = from c in customers.Descendants("customer").Attribute("Company")
                                                                            //返回指定属性对象:Company=“Toms Spezialit”
                                      select c.Value;    //用Value属性获得属性值 
                  int min = queryResults.Min(); //取记录中的最小值

posted on 2011-07-15 16:05  骑着毛驴去编程  阅读(157)  评论(0编辑  收藏  举报

导航