使用Linq to XML遍历XML

来源:互联网 发布:矩阵的lu分解如何计算 编辑:程序博客网 时间:2024/06/06 03:48

using System;
using System.Xml.Linq;
using System.Linq;

namespace ConsoleApplication1
{
   
class Program
    {
       
static void Main(string[] args)
        {
           
//保存
            XElement xel = XElement.Parse(@"
<Root>
  <Persons>
    <Person>Huang Cong</Person>
    <Person>Zhang San</Person>
    <Person>Li Si</Person>
    <Person>Wang Wu</Person>
  </Persons>
</Root>
");
            Console.WriteLine(
"使用XNode遍历:");
           
foreach (XNode n in xel.Nodes())
            {
                Console.WriteLine(n);
            }
            Console.WriteLine(
"----------------------------");
            Console.WriteLine(
"使用XElement遍历:");
           
foreach (XElement e in xel.Elements("Persons"))
            {
                Console.WriteLine(e);
            }
            Console.WriteLine(
"----------------------------");
            Console.WriteLine(
"使用Lambda表达式遍历:");
            var query
= xel.Elements().Select(u => u);
           
foreach (var q in query)
            {
                Console.WriteLine(q);
            }
        }
    }
}

原创粉丝点击