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

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

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

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

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

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

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

    1. foreach (XAttribute a in xa)
    1. if (a.Name.ToString() == "Type")
    1. Console.WriteLine(a.Value);
    1. XElement cust = new XElement("PhoneNumbers",
    1. new XElement("Phone",
    1. new XAttribute("type","home"),
    1. "555-555-5555"),
    1. new XElement("Phone",
    1. new XAttribute("type","work"),
    1. "555-555-6666")
    1. );

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

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

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

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

    1. foreach (XElement el in purchaSEOrders)
    1. Console.WriteLine((string)el.Attribute("PurchaSEOrderNumber"));
    1. //筛选可选元素
    1. XElement root = XElement.Parse(@"<Root>
    1. <Child1>
    1. <Text>Child One Text</Text>
    1. <Type Value=""Yes""/>
    1. </Child1>
    1. <Child2>
    1. <Text>Child Two Text</Text>
    1. <Type Value=""Yes""/>
    1. </Child2>
    1. <Child3>
    1. <Text>Child Three Text</Text>
    1. <Type Value=""No""/>
    1. </Child3>
    1. <Child4>
    1. <Text>Child Four Text</Text>
    1. <Type Value=""Yes""/>
    1. </Child4>
    1. <Child5>
    1. <Text>Child Five Text</Text>
    1. </Child5>
    1. </Root>");
    1. var cList = from typeElement in root.Elements().Elements("Type")
    1. where (string)typeElement.Attribute("Value") == "Yes"
    1. select (string)typeElement.Parent.Element("Text");

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

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

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

    1. foreach (decimal ex in extensions)
    1. Console.WriteLine(ex);

    1. //编写基于上下文查找元素的查询
    1. XElement doc = XElement.Parse(@"<Root>
    1. <p id=""1""/>
    1. <ul>abc</ul>
    1. <Child>
    1. <p id=""2""/>
    1. <notul/>
    1. <p id=""3""/>
    1. <ul>def</ul>
    1. <p id=""4""/>
    1. </Child>
    1. <Child>
    1. <p id=""5""/>
    1. <notul/>
    1. <p id=""6""/>
    1. <ul>abc</ul>
    1. <p id=""7""/>
    1. </Child>
    1. </Root>");

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

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

    1. Dictionary<string,string>();

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

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

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

猜你在找的XML相关文章