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","medium") ),new XElement("third","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.Color.Value,item.Size.Value); }</span>原文链接:https://www.f2er.com/xml/297686.html