LINQ to XML简介(2)

来源:互联网 发布:vb insert into 语法 编辑:程序博客网 时间:2024/04/29 14:02

1.可以把LINQ XML API和LINQ查询表达式组合在一起产生简单而强大的XML树搜索

创建XML树,如下所示代码:

<span style="font-size:18px;"> XDocument xTree = new XDocument(                new XElement("MyElement",                    new XElement("first",                        new XAttribute("color","red"),                        new XAttribute("size","small")                        ),                        new XElement("second",                        new XAttribute("color","red"),                        new XAttribute("size","medium")                        ),                        new XElement("third",                        new XAttribute("color","red"),                        new XAttribute("size","large")                        )                    )                );</span>

产生如下输出:

2.使用LINQ查询如下所示:

<span style="font-size:18px;"> xTree.Save("XTreeTest.xml");            XDocument doc = XDocument.Load("XTreeTest.xml");            XElement root = doc.Element("MyElement");            IEnumerable<XElement> xElements= root.Elements();            //找出根节点下节点名称为5个字符的节点            var query = from x in xElements                        where x.Name.ToString().Length == 5                        select x;            foreach (var item in query)            {                Console.WriteLine("Name:{0}",item.Name);            }            foreach (var item in query)            {                Console.WriteLine("Name:{0},color:{1},size:{2}",item.Name,item.Attribute("color").Value,item.Attribute("size").Value);            }</span>

输出如下:

或者使用Select创建匿名类实例

<span style="font-size:18px;">var xyz = from e in xElements                      select new {e.Name,Color=e.Attribute("color"),Size=e.Attribute("size") };            foreach (var item in xyz)            {                Console.WriteLine("Name:{0},Color:{1}.Size:{2}",item.Name,item.Color.Value,item.Size.Value);            }</span>


0 0
原创粉丝点击