LINQ to XML 的简单应用

1.  创建XML文档

static void Main(string[] args)
    {
      CreateMusicLibrary();
    }

    static void CreateMusicLibrary()
    {
      XDocument musicLibrary =
        new XDocument(
          new XDeclaration("1.0", "utf-8", "yes"),
            //new XProcessingInstruction("xml-stylesheet", "href='music.xslt'"),
            new XComment("This document holds details of my music collection"),
            new XElement("musicLibrary",
              CreateCDElement("1", "Parallel Lines", 2001, "Blondie", "New Wave"),
              CreateCDElement("2", "Bat Out of Hell", 2001, "Meatloaf", "Rock"),
              CreateCDElement("3", "Abbey Road", 1987, "The Beatles", "Rock"),
              CreateCDElement("4", "The Dark Side of the Moon", 1994, "Pink Floyd", "Rock"),
              CreateCDElement("5", "Thriller", 2001, "Michael Jackson", "Pop")));
      Console.WriteLine(musicLibrary.ToString());    //使用ToString方法显示XML文档时会忽略文档中的声明
      Console.ReadLine();
    }

    static XElement CreateCDElement(string id, string title, int year, string artist, string genre)
    {
      return new XElement("cd",
              new XAttribute("id", id),
              new XElement("title", title),
              new XElement("year", year),
              new XElement("artist", artist),
              new XElement("genre", genre));
    }

1.1 创建带名称空间的文档,并把名称空间声明为默认名称空间:

static void CreateMusicLibrary()
    {
      XNamespace ns = "http://www.wrox.com/namespaces/apps/musicLibrary";   //使用XNamespace类声明命名空间,并将其应用到元素和属性上
      XElement musicLibrary =
        new XElement(ns + "musicLibrary",
          CreateCDElement(ns, "1", "Parallel Lines", 2001, "Blondie", "New Wave"),
          CreateCDElement(ns, "2", "Bat Out of Hell", 2001, "Meatloaf", "Rock"),
          CreateCDElement(ns, "3", "Abbey Road", 1987, "The Beatles", "Rock"),
          CreateCDElement(ns, "4", "The Dark Side of the Moon", 1994, "Pink Floyd", "Rock"),
          CreateCDElement(ns, "5", "Thriller", 2001, "Michael Jackson", "Pop"));
      Console.WriteLine(musicLibrary.ToString());
      Console.ReadLine();
    }

    static XElement CreateCDElement(XNamespace ns, string id, string title, int year, string artist, string genre)
    {
      return new XElement(ns + "cd",
              new XAttribute("id", id),
              new XElement(ns + "title", title),
              new XElement(ns + "year", year),
              new XElement(ns + "artist", artist),
              new XElement(ns + "genre", genre));
    }

1.2 创建带有前缀名的名称空间文档

  static void Main(string[] args)
    {
      CreateMusicLibrary();
    }

    static void CreateMusicLibrary()
    {
      XNamespace ns = "http://www.wrox.com/namespaces/apps/musicLibrary";
      XElement musicLibrary =
        new XElement(ns + "musicLibrary",
          new XAttribute(XNamespace.Xmlns + "ns", ns.NamespaceName),          //使用XAttribute类将命名空间URI映射到前缀名上
          CreateCDElement(ns, "1", "Parallel Lines", 2001, "Blondie", "New Wave"),
          CreateCDElement(ns, "2", "Bat Out of Hell", 2001, "Meatloaf", "Rock"),
          CreateCDElement(ns, "3", "Abbey Road", 1987, "The Beatles", "Rock"),
          CreateCDElement(ns, "4", "The Dark Side of the Moon", 1994, "Pink Floyd", "Rock"),
          CreateCDElement(ns, "5", "Thriller", 2001, "Michael Jackson", "Pop"));
      Console.WriteLine(musicLibrary.ToString());
      Console.ReadLine();
    }

    static XElement CreateCDElement(XNamespace ns, string id, string title, int year, string artist, string genre)
    {
      return new XElement(ns + "cd",
              new XAttribute("id", id),
              new XElement(ns + "title", title),
              new XElement(ns + "year", year),
              new XElement(ns + "artist", artist),
              new XElement(ns + "genre", genre));
    }


2. 从XML 文档中提取数据

需要查询的xml文档如下:

<?xml version="1.0" encoding="utf-8"?>
<musicLibrary>
  <cd id="1">
    <title>Parallel Lines</title>
    <year>2001</year>
    <artist>Blondie</artist>
    <genre>New Wave</genre>
  </cd>
  <cd id="2">
    <title>Bat Out of Hell</title>
    <year>2001</year>
    <artist>Meatloaf</artist>
    <genre>Rock</genre>
  </cd>
  <cd id="3">
    <title>Abbey Road</title>
    <year>1987</year>
    <artist>The Beatles</artist>
    <genre>Rock</genre>
  </cd>
  <cd id="4">
    <title>The Dark Side of the Moon</title>
    <year>1994</year>
    <artist>Pink Floyd</artist>
    <genre>Rock</genre>
  </cd>
  <cd id="5">
    <title>Thriller</title>
    <year>2001</year>
    <artist>Michael Jackson</artist>
    <genre>Pop</genre>
  </cd>
</musicLibrary>
要使用LINQ to XML,需要引用System.Xml.Linq程序集

 static void Main(string[] args)
    {
      XElement musicLibrary = XElement.Load(@"MusicLibrary.xml");
      Console.WriteLine("All Titles\n==========");
      ShowTitles(musicLibrary);
      Console.WriteLine("\nTitles before CD 3\n==================");
      ShowTitlesBefore(musicLibrary);
      Console.WriteLine("\nTitles after CD 3\n=================");
      ShowTitlesAfter(musicLibrary);
      Console.WriteLine("\nTitles by Genre\n===============");
      GroupOnGenre(musicLibrary);
      Console.ReadLine();
    }

    static void ShowTitles(XElement musicLibrary)
    {
      foreach (XElement t in musicLibrary.Elements("cd").Elements("title"))
      // alternative using Descendants method.
      // foreach (XElement t in musicLibrary.Descendants("title"))
      {
        Console.WriteLine(t.Value);
      }
    }

    static void ShowTitlesBefore(XElement musicLibrary)
    {
      XElement cd3 = (from cd in musicLibrary.Elements("cd")
                      where cd.Attribute("id").Value == "3"
                      select cd).FirstOrDefault();
      foreach (XElement t in cd3.ElementsBeforeSelf("cd").Elements("title"))
      {
        Console.WriteLine(t.Value);
      }
    }

    static void ShowTitlesAfter(XElement musicLibrary)
    {
      XElement cd3 = musicLibrary.Elements("cd").Where(cd => cd.Attribute("id").Value == "3").FirstOrDefault();
      foreach (XElement t in cd3.ElementsAfterSelf("cd").Elements("title"))
      {
        Console.WriteLine(t.Value);
      }
    }

    static void GroupOnGenre(XElement musicLibrary)
    {
      var groupQuery = from cd in musicLibrary.Elements("cd")
                        group cd by cd.Element("genre").Value into genreGroup
                        orderby genreGroup.Key
                        select new
                        {
                          Genre = genreGroup.Key,
                          Titles = from title in genreGroup.Elements("title")
                                  select title.Value
                        };
      foreach (var entry in groupQuery)
      {
        Console.WriteLine("Genre: {0}", entry.Genre);
        Console.WriteLine("----------------");
        foreach (var title in entry.Titles)
        {
          Console.WriteLine("\t{0}", title);
        }
        Console.WriteLine();
      }
    }
运行结果如下:

3. 修改XML文档

 static void Main(string[] args)
    {
      XElement musicLibrary = XElement.Load(@"MusicLibrary.xml");
      Console.WriteLine("Adding a New CD\n===============");
      AddNewCD(musicLibrary);
      Console.WriteLine(musicLibrary);
      Console.WriteLine("\nRemoving a CD=============");
      RemoveCD(musicLibrary);
      Console.WriteLine(musicLibrary);
      Console.WriteLine("\nAdding a New CD Directly\n========================");
      AddNewCDDirectly(musicLibrary);
      Console.WriteLine(musicLibrary);
      Console.WriteLine("\nUpdate Year with ReplaceNodes\n=============================");
      UpdateYearWithReplaceNodes(musicLibrary);
      Console.WriteLine(musicLibrary);
      Console.WriteLine("\nUpdate Year with SetElementValue================================");
      UpdateYearWithSetElementValue(musicLibrary);
      Console.WriteLine(musicLibrary);
      Console.WriteLine("\nUpdate Attribute Value====================");
      UpdateAttributeValue(musicLibrary);
      Console.WriteLine(musicLibrary);
      Console.WriteLine("\nReplace CD Content==================");
      ReplaceCD(musicLibrary);
      Console.WriteLine(musicLibrary);
      Console.ReadLine();
    }

    static void AddNewCD(XElement musicLibrary)
    {
      XElement cd = CreateCDElement("6", "Back in Black", 2003, "AC/DC", "Rock");
      musicLibrary.Add(cd);
    }

    static void AddNewCDDirectly(XElement musicLibrary)
    {
      musicLibrary.Add(
          new XElement("cd",
            new XAttribute("id", 6),
            new XElement("title", "Back in Black"),
            new XElement("year", 2003),
            new XElement("artist", "AC/DC"),
            new XElement("genre", "Rock")));
    }

    static void RemoveCD(XElement musicLibrary)
    {
      XElement cd = (from entry in musicLibrary.Elements("cd")
                     where entry.Attribute("id").Value == "6"
                     select entry).FirstOrDefault();
      if (null != cd)
      {
        cd.Remove();
      }
    }

    static XElement CreateCDElement(string id, string title, int year, string artist, string genre)
    {
      return new XElement("cd",
              new XAttribute("id", id),
              new XElement("title", title),
              new XElement("year", year),
              new XElement("artist", artist),
              new XElement("genre", genre));
    }

    static void UpdateYearWithReplaceNodes(XElement musicLibrary)
    {
      XElement cd = (from entry in musicLibrary.Elements("cd")
                     where entry.Attribute("id").Value == "3"
                     select entry).FirstOrDefault();
      cd.Element("year").ReplaceNodes("1986");
    }

    static void UpdateYearWithSetElementValue(XElement musicLibrary)
    {
      XElement cd = (from entry in musicLibrary.Elements("cd")
                     where entry.Attribute("id").Value == "3"
                     select entry).FirstOrDefault();
      cd.SetElementValue("year", "1987");
    }

    static void UpdateAttributeValue(XElement musicLibrary)
    {
      XElement cd = (from entry in musicLibrary.Elements("cd")
                     where entry.Attribute("id").Value == "3"
                     select entry).FirstOrDefault();
      cd.SetAttributeValue("id", "7");
    }

    static void ReplaceCD(XElement musicLibrary)
    {
      XElement cd = (from entry in musicLibrary.Elements("cd")
                      where entry.Attribute("id").Value == "1"
                      select entry).FirstOrDefault();

      cd.ReplaceWith( new XElement("cd",
                        new XAttribute("id", 1),
                        new XElement("title", "Back in Black"),
                        new XElement("year", 2003),
                        new XElement("artist", "AC/DC"),
                        new XElement("genre", "Rock")));
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 《LINQ高级编程》是由Joe Duffy编写的一本关于LINQ(即语言集成查询)的高级编程指南。这本书通过深入解析LINQ的原理和内部机制,帮助读者掌握如何使用LINQ进行高效的数据查询和处理。 该书的内容包括LINQ查询语法、Lambda表达式、LINQ to Objects、LINQ to XMLLINQ to SQL、LINQ to Entities以及一些高级主题,如并行LINQ和自定义LINQ提供程序。书中通过大量的代码示例和详细的解释,引导读者逐步掌握LINQ的各种技术和用法。 在《LINQ高级编程》中,作者还特别强调了LINQ的一些优势,包括提供了一种统一的语法,使得查询和处理各种数据源变得简单、灵活;通过延迟加载的机制,实现了惰性查询,从而提高了性能和资源利用率;支持LINQ查询的各种数据源包括集合、XML文档、关系数据库等,可以满足不同场景下的数据处理需求。 这本书适合有一定编程基础的读者阅读,特别是对LINQ和数据查询感兴趣的开发者和学习者。通过学习《LINQ高级编程》,读者可以掌握LINQ的核心理念和用法,并能够灵活运用LINQ进行数据查询、过滤和处理,提高编程效率和质量。 总之,如果你对LINQ感兴趣并想要深入了解它的原理和应用,那么《LINQ高级编程》这本书将是一个很好的选择。它通过详细的解释和丰富的示例,帮助读者全面掌握LINQ的高级编程技术,并将其应用于实际项目中。 ### 回答2: 《LINQ高级编程》是一本介绍LINQ(Language Integrated Query)技术的书籍。LINQ是微软在.NET框架中推出的一种查询技术,它允许在编程语言中直接嵌入查询语句,从而使开发人员能够以一种统一的方式查询各种数据源,包括对象集合、关系数据库、XML文档等。 《LINQ高级编程》这本书全面介绍了LINQ技术的方方面面,从基础概念开始讲解,包括LINQ的语法、查询操作符、延迟执行等。然后深入介绍了LINQ提供的不同数据源的查询方式,如LINQ to Objects、LINQ to SQL、LINQ to XML等。同时,还讨论了LINQ与其他相关技术的结合应用,如LINQ和Entity Framework的结合,LINQ和ASP.NET MVC的结合等。 这本书通过清晰的语言和丰富的示例代码,帮助读者深入了解LINQ的核心思想和使用技巧。读者可以通过学习本书,掌握LINQ技术的基本原理,提高自己的编程水平,并且能够更高效地处理各种数据查询操作。 总之,《LINQ高级编程》是一本很好的LINQ技术入门书籍,无论是对于想要学习LINQ的初学者,还是对于有一定LINQ基础的开发人员来说,都能从中获得很多有用的知识和经验。阅读本书对于提升自己的编程能力和应用LINQ技术解决实际问题都是非常有帮助的。 ### 回答3: LINQ高级编程是一本关于LINQ(Language Integrated Query)的编程技术的PDF书籍。LINQ是微软开发的一种数据访问技术,提供了一种统一的查询语言,使得在不同的数据源上进行查询变得简单和方便。这本书深入介绍了LINQ的高级概念和用法,帮助读者更好地理解并掌握LINQ编程。 书中首先介绍了LINQ的基础知识,包括LINQ查询表达式的语法和基本查询操作符。然后,书籍逐步深入,讲解了更高级的LINQ概念,如连接查询、分组查询、聚合操作等。通过大量的实例和案例,读者可以学习如何使用LINQ在各种数据源(如SQL数据库、XML文档、集合等)上进行复杂的查询和操作。 此外,书中还提供了一些关于性能优化、错误处理和异步编程等方面的实用技巧。读者可以学习如何通过使用合适的查询方法和技巧来提高LINQ查询的效率,并避免常见的错误和陷阱。 总体而言,这本《LINQ高级编程》的PDF书籍是一本详尽而全面的关于LINQ编程的指南。无论是初学者还是有一定经验的开发者,都可以从中获得实用的知识和技巧,并将其应用到实际的项目中。如果你对LINQ感兴趣,想要提升自己的LINQ编程水平,这本书是一个不错的选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值