LINQ to XML 轴

前端之家收集整理的这篇文章主要介绍了LINQ to XML 轴前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

定义:
创建XML树或将XML文档加载到XML树之后,可以进行查询,从而查找元素并检索它们的值。


两类轴方法
-一些轴就是XELement和XDocument类中返回IEnumerable(T)集合的方法
-另一些轴方法是Extensions类中的扩展方法。实现为扩展方法的轴对集合进行操作,然后返回集合。
XContainer是XElement的基类!


-
常见的轴方法
-XContainer.Elements()返回集合


-XContainer.Descendants()返回集合


-XContainer.Element()返回单个元素


-XElement.Attribute(XName)返回单个属性


-XElement.Attributes(XName)返回所有属性集合


下面是XElement类(或其基类)的方法汇总,可以对XElement调用这些方法以返回元素集合
-XNode.Ancestors 返回此元素的上级的XElement的IEnumerable(T)


-XContainer.Descendants 返回此元素的子代的XElement的IEnumerable(T)


-XContainer.Elements 返回此元素的子元素XElement的IEnumerable(T)


-XNode.ElementsAfterSelf 返回此元素之后的元素的XElement的IEnumerable(T)


-XNode.ElementsBeforeSelf 返回此元素之前的元素的XElement的IEnumerable(T)


-XElement.AncestorsAndSelf 返回此元素及其上级的XElement的IEnumerable(T)


-XElementDescendantsAndSelf 返回此元素及其子代的XElement的IEnumerable(T)


如何获取元素的值,有两种主要方法可以完成此操作
– 一种方法是将XElement 或XAttribute 强制转换为所需的类型。然后,显式转换运算符将元素或属性内容转换为指定的类型,并将其分配给变量。


– 此外,还可以使用XElement.Value 属性或XAttribute.Value 属性,但是,对于C#,强制转换通常是更好的方法。在检索可能存在也可能不存在的元素(或属性)的值时,如果将元素或属性强制转换为可以为null 的类型,则代码会更易于编写无法通过强制转换设置元素的内容,而通过XElement.Value 属性可以做到这一点。

实例代码

  1. /////检索元素的值
    
  2. XElement e = new XElement("StringElement","abcd");
    
  3. Console.WriteLine(e);
    
  4. Console.WriteLine("Value of e:" + (string)e);
    
  5. Console.WriteLine("Value of e by Value:" + e.Value);
    
  1. //检索元素集合
    
  2. XElement po = XElement.Load("PurchaSEOrder.xml");
    
  3. IEnumerable<XElement> childElements = from el in po.Elements()
    
  4.                                       select el;
    

  5. foreach (XElement el in childElements)
    
  6.     Console.WriteLine("Name: " + el.Name);
    
  1. ////根据元素的名称进行筛选
    
  2. XElement po = XElement.Load("PurchaSEOrder.xml");
    
  3. IEnumerable<XElement> items = from el in po.Descendants("ProductName")
    
  4.                               select el;
    

  5. foreach (XElement proName in items)
    
  6.     Console.Write("PrdName" + ":" + (string)proName);
    

  1. ////根据元素的名称进行筛选(有命名空间)
    
  2. XNamespace aw = "http://www.adventure-works.com";
    
  3. XElement po = XElement.Load("PurchaSEOrderInNamespace.xml");
    
  4. IEnumerable<XElement> items = from el in po.Descendants(aw + "ProductName")
    
  5.                               select el;
    

  6. foreach (XElement prdName in items)
    
  7.     Console.WriteLine(prdName.Name + ":" + (string)prdName);
    
  1. ////链接方法,有时,当可能存在或不存在间隔上级时,您希望在特定的元素深度,检索所有的元素
    
  2. XElement root = XElement.Load("Irregular.xml");
    
  3. IEnumerable<XElement> configParameters =root.Elements("Customer").Elements("Config").
    
  4.                                         Elements("ConfigParameter");
    

  5. foreach (XElement cp in configParameters)
    
  6.     Console.WriteLine(cp.Value);
    
  1. ////检索单个子元素
    
  2. XElement po = XElement.Load("PurchaSEOrder.xml");
    
  3. XElement e = po.Element("DeliveryNotes");
    
  4. Console.WriteLine(e);
    
  1. ////检索属性type的值
    
  2. XElement val = new XElement("Value",
  3.                                     new XAttribute("ID","1243"),
  4.                                     new XAttribute("Type","int"),
  5.                                     new XAttribute("ConvertableTo","double"),
  6.                             "100");
    

  7. IEnumerable<XAttribute> xa = from att in val.Attributes()
    
  8.                              select att;
    

  9. foreach (XAttribute a in xa)
    
  10.     if (a.Name.ToString() == "Type")
    
  11.         Console.WriteLine(a.Value);
    
  1. XElement cust = new XElement("PhoneNumbers",
  2.                              new XElement("Phone",
  3.                              new XAttribute("type","home"),
  4.                      "555-555-5555"),
  5.                  new XElement("Phone",
  6.                              new XAttribute("type","work"),
  7.                      "555-555-6666")
    
  8.              );
    

  9. IEnumerable<XElement> elList = from el in cust.Descendants("Phone")
    
  10.                                select el;
    

  11. foreach (XElement el in elList)
    
  12.     Console.WriteLine((string)el.Attribute("type"));
    
  1. ////查找具有特定属性的元素
    
  2. XElement root = XElement.Load("PurchaSEOrder.xml");
    
  3. IEnumerable<XElement> address = from el in root.Elements("Address")
    
  4.                                 where (string)el.Attribute("Type") == "Billing"
    
  5.                                 select el;
    

  6. foreach (XElement el in address)
    
  7.     Console.WriteLine(el);
    
  1. ////查找具有特定子元素的元素
    
  2. XElement root = XElement.Load("TestConfig.xml");
    
  3. IEnumerable<XElement> tests = from el in root.Elements("Test")
    
  4.                               where (string)el.Element("CommandLine") == "Examp2.EXE"
    
  5.                               select el;
    

  6. foreach (XElement el in tests)
    
  7.     Console.WriteLine((string)el.Attribute("TestId"));
    
  1. ////编写使用复杂筛选的查询
    
  2. XElement root = XElement.Load("PurchaSEOrders.xml");
    
  3. IEnumerable<XElement> purchaSEOrders = from el in root.Elements("PurchaSEOrder")
    
  4.                                        where
    
  5.                                            (from add in el.Elements("Address")
    
  6.                                             where
    
  7.                                                 (string)add.Attribute("Type") == "Shipping" &&
    
  8.                                                 (string)add.Element("State") == "NY"
    
  9.                                             select add)
    
  10.                                            .Any()
    
  11.                                        select el;
    

  12. foreach (XElement el in purchaSEOrders)
    
  13.     Console.WriteLine((string)el.Attribute("PurchaSEOrderNumber"));
    
  1. //筛选可选元素
    
  2. XElement root = XElement.Parse(@"<Root>
    
  3.               <Child1>
    
  4.                 <Text>Child One Text</Text>
    
  5.                 <Type Value=""Yes""/>
    
  6.               </Child1>
    
  7.               <Child2>
    
  8.                 <Text>Child Two Text</Text>
    
  9.                 <Type Value=""Yes""/>
    
  10.               </Child2>
    
  11.               <Child3>
    
  12.                 <Text>Child Three Text</Text>
    
  13.                 <Type Value=""No""/>
    
  14.               </Child3>
    
  15.               <Child4>
    
  16.                 <Text>Child Four Text</Text>
    
  17.                 <Type Value=""Yes""/>
    
  18.               </Child4>
    
  19.               <Child5>
    
  20.                 <Text>Child Five Text</Text>
    
  21.               </Child5>
    
  22.             </Root>");
    
  23. var cList = from typeElement in root.Elements().Elements("Type")
    
  24.             where (string)typeElement.Attribute("Value") == "Yes"
    
  25.             select (string)typeElement.Parent.Element("Text");
    

  26. foreach (string str in cList)
    
  27.     Console.WriteLine(str);
    
  1. //对元素进行排序
    
  2. XElement root = XElement.Load("Data.xml");
    
  3. IEnumerable<decimal> prices = from el in root.Elements("Data")
    
  4.                               let price = (decimal)el.Element("Price")
    
  5.                               orderby price
    
  6.                               select price;
    

  7. foreach (decimal el in prices)
    
  8.     Console.WriteLine(el);
    
  1. //对多个键上的元素进行排序
    
  2. XElement co = XElement.Load("CustomersOrders.xml");
    
  3. var sortedElements = from c in co.Element("Orders").Elements("Order")
    
  4.                      orderby (string)c.Element("ShipInfo").Element("ShipPostalCode"),
  5.                              (DateTime)c.Element("OrderDate")
    
  6.                      select new
    
  7.                      {
    
  8.                          CustomerID = (string)c.Element("CustomerID"),
  9.                          EmployeeID = (string)c.Element("EmployeeID"),
  10.                          ShipPostalCode = (string)c.Element("ShipInfo").Element("ShipPostalCode"),
  11.                          OrderDate = (DateTime)c.Element("OrderDate")
    
  12.                      };
    

  13. foreach (var r in sortedElements)
    
  14.     Console.WriteLine("CustomerID:{0} EmployeeID:{1} ShipPostalCode:{2} OrderDate:{3:d}",
  15.         r.CustomerID,r.EmployeeID,r.ShipPostalCode,r.OrderDate);
    
  1. ////计算中间值
    
  2. XElement root = XElement.Load("Data.xml");
    
  3. IEnumerable<decimal> extensions = from el in root.Elements("Data")
    
  4.                                   let extension = (decimal)el.Element("Quantity") * (decimal)el.Element("Price")
    
  5.                                   where extension >= 25
    
  6.                                   orderby extension
    
  7.                                   select extension;
    

  8. foreach (decimal ex in extensions)
    
  9.     Console.WriteLine(ex);
    

  1. //编写基于上下文查找元素的查询
    
  2. XElement doc = XElement.Parse(@"<Root>
    
  3.                 <p id=""1""/>
    
  4.                 <ul>abc</ul>
    
  5.                 <Child>
    
  6.                     <p id=""2""/>
    
  7.                     <notul/>
    
  8.                     <p id=""3""/>
    
  9.                     <ul>def</ul>
    
  10.                     <p id=""4""/>
    
  11.                 </Child>
    
  12.                 <Child>
    
  13.                     <p id=""5""/>
    
  14.                     <notul/>
    
  15.                     <p id=""6""/>
    
  16.                     <ul>abc</ul>
    
  17.                     <p id=""7""/>
    
  18.                 </Child>
    
  19.             </Root>");
    

  20. IEnumerable<XElement> items = from e in doc.Descendants("p")
    
  21.                               let z = e.ElementsAfterSelf().FirstOrDefault()
    
  22.                               where z != null && z.Name.LocalName == "ul"
    
  23.                               select e;
    

  24. foreach (XElement e in items)
    
  25.     Console.WriteLine("id = {0}",(string)e.Attribute("id"));
    
  1. //通过 LINQ to XML 使用字典
    
  2. Dictionary<string,string> dict = new Dictionary<string,string>();
    
  3. dict.Add("Child1","Value1");
    
  4. dict.Add("Child2","Value2");
    
  5. dict.Add("Child3","Value3");
    
  6. dict.Add("Child4","Value4");
    
  7. XElement root = new XElement("Root",
  8.       from keyValue in dict
    
  9.       select new XElement(keyValue.Key,keyValue.Value)
    
  10. );
    
  1. XElement root = XElement.Load("Data.xml");
    

  2. Dictionary<string,string>();
    

  3. foreach (XElement el in root.Elements())
    
  4.     dict.Add(el.Name.LocalName,el.Value);
    

  5. foreach (string str in dict.Keys)
    
  6.     Console.WriteLine("{0}:{1}",str,dict[str]);
    

  7. Console.WriteLine(root);
    
转自: http://www.cnblogs.com/lynstone/archive/2009/09/26/1574162.html

猜你在找的XML相关文章