XML(3)——Linq To XML:读
作者:互联网
1、XDocument doc = XDocument.Load(reader),加载XML文件,XDocument就是加载的对象。
2、解析订单号:doc.Root.Element("OrderNumber").Value
3、遍历订单项:
foreach (XElement element in doc.Root.Descendants("Items").Descendants("OrderItem"))
{
Console.WriteLine("商品名:{0},数量:{1}", element.Element("ItemName").Value, element.Element("Count").Value);
}
4、读取属性,Attribute(""),读取带属性的订单:
foreach (XElement element in doc.Root.Descendants("Items").Descendants("OrderItem"))
{
Console.WriteLine("商品名:{0},数量:{1}", element.Attribute("Name").Value, element.Attribute("Count").Value);
}
5、使用Linq来进行XML的操作,代码如下:
(1)读取XML第一版:
StreamReader reader = new StreamReader(@"c:\1.xml");
XDocument doc = XDocument.Load(reader);
Console.WriteLine("订单号{0}", doc.Root.Element("OrderNumber").Value);
foreach (XElement element in doc.Root.Descendants("Items").Descendants("OrderItem"))
{
Console.WriteLine("商品名:{0},数量:{1}", element.Element("ItemName").Value, element.Element("Count").Value);
}
(2)带属性的订单xml:
<?xml version="1.0"?>
<Order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CustomerName>杨中科</CustomerName>
<OrderNumber>BJ200888</OrderNumber>
<Items>
<OrderItem Name="电脑" Count="30"/>
<OrderItem Name="电视" Count="2"/>
<OrderItem Name="水杯" Count="20"/>
</Items>
</Order>
(3)
var result = from element in doc.Root.Descendants("Items").Descendants("OrderItem")
where int.Parse(element.Attribute("Count").Value)>10
select new { Name = element.Attribute("Name").Value, Count = element.Attribute("Count").Value };
foreach (var item in result)
{
Console.WriteLine("商品名{0},数量{1}",item.Name,item.Count);
}
标签:XML,Count,Descendants,doc,Value,element,Linq,Element 来源: https://blog.csdn.net/qq_34573534/article/details/100586027