LINQ to XML 的简单应用

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

1. 创建XML文档

  1. static void Main(string[] args)
  2. {
  3. CreateMusicLibrary();
  4. }
  5.  
  6. static void CreateMusicLibrary()
  7. {
  8. XDocument musicLibrary =
  9. new XDocument(
  10. 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","Meatloaf","Rock"),CreateCDElement("3","Abbey Road",1987,"The Beatles",CreateCDElement("4","The Dark Side of the Moon",1994,"Pink Floyd",CreateCDElement("5","Thriller","Michael Jackson","Pop")));
  11. Console.WriteLine(musicLibrary.ToString()); //使用ToString方法显示XML文档时会忽略文档中的声明
  12. Console.ReadLine();
  13. }
  14.  
  15. static XElement CreateCDElement(string id,string title,int year,string artist,string genre)
  16. {
  17. return new XElement("cd",new XAttribute("id",id),new XElement("title",title),new XElement("year",year),new XElement("artist",artist),new XElement("genre",genre));
  18. }

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

  1. static void CreateMusicLibrary()
  2. {
  3. XNamespace ns = "http://www.wrox.com/namespaces/apps/musicLibrary"; //使用XNamespace类声明命名空间,并将其应用到元素和属性
  4. XElement musicLibrary =
  5. new XElement(ns + "musicLibrary",CreateCDElement(ns,"1","2","3","4","5","Pop"));
  6. Console.WriteLine(musicLibrary.ToString());
  7. Console.ReadLine();
  8. }
  9.  
  10. static XElement CreateCDElement(XNamespace ns,string id,string genre)
  11. {
  12. return new XElement(ns + "cd",new XElement(ns + "title",new XElement(ns + "year",new XElement(ns + "artist",new XElement(ns + "genre",genre));
  13. }

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

  1. static void Main(string[] args)
  2. {
  3. CreateMusicLibrary();
  4. }
  5.  
  6. static void CreateMusicLibrary()
  7. {
  8. XNamespace ns = "http://www.wrox.com/namespaces/apps/musicLibrary";
  9. XElement musicLibrary =
  10. new XElement(ns + "musicLibrary",new XAttribute(XNamespace.Xmlns + "ns",ns.NamespaceName),//使用XAttribute类将命名空间URI映射到前缀名上
  11. CreateCDElement(ns,genre));
  12. }


2. 从XML 文档中提取数据

需要查询的xml文档如下:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <musicLibrary>
  3. <cd id="1">
  4. <title>Parallel Lines</title>
  5. <year>2001</year>
  6. <artist>Blondie</artist>
  7. <genre>New Wave</genre>
  8. </cd>
  9. <cd id="2">
  10. <title>Bat Out of Hell</title>
  11. <year>2001</year>
  12. <artist>Meatloaf</artist>
  13. <genre>Rock</genre>
  14. </cd>
  15. <cd id="3">
  16. <title>Abbey Road</title>
  17. <year>1987</year>
  18. <artist>The Beatles</artist>
  19. <genre>Rock</genre>
  20. </cd>
  21. <cd id="4">
  22. <title>The Dark Side of the Moon</title>
  23. <year>1994</year>
  24. <artist>Pink Floyd</artist>
  25. <genre>Rock</genre>
  26. </cd>
  27. <cd id="5">
  28. <title>Thriller</title>
  29. <year>2001</year>
  30. <artist>Michael Jackson</artist>
  31. <genre>Pop</genre>
  32. </cd>
  33. </musicLibrary>
要使用LINQ to XML,需要引用System.Xml.Linq程序集
  1. static void Main(string[] args)
  2. {
  3. XElement musicLibrary = XElement.Load(@"MusicLibrary.xml");
  4. Console.WriteLine("All Titles\n==========");
  5. ShowTitles(musicLibrary);
  6. Console.WriteLine("\nTitles before CD 3\n==================");
  7. ShowTitlesBefore(musicLibrary);
  8. Console.WriteLine("\nTitles after CD 3\n=================");
  9. ShowTitlesAfter(musicLibrary);
  10. Console.WriteLine("\nTitles by Genre\n===============");
  11. GroupOnGenre(musicLibrary);
  12. Console.ReadLine();
  13. }
  14.  
  15. static void ShowTitles(XElement musicLibrary)
  16. {
  17. foreach (XElement t in musicLibrary.Elements("cd").Elements("title"))
  18. // alternative using Descendants method.
  19. // foreach (XElement t in musicLibrary.Descendants("title"))
  20. {
  21. Console.WriteLine(t.Value);
  22. }
  23. }
  24.  
  25. static void ShowTitlesBefore(XElement musicLibrary)
  26. {
  27. XElement cd3 = (from cd in musicLibrary.Elements("cd")
  28. where cd.Attribute("id").Value == "3"
  29. select cd).FirstOrDefault();
  30. foreach (XElement t in cd3.ElementsBeforeSelf("cd").Elements("title"))
  31. {
  32. Console.WriteLine(t.Value);
  33. }
  34. }
  35.  
  36. static void ShowTitlesAfter(XElement musicLibrary)
  37. {
  38. XElement cd3 = musicLibrary.Elements("cd").Where(cd => cd.Attribute("id").Value == "3").FirstOrDefault();
  39. foreach (XElement t in cd3.ElementsAfterSelf("cd").Elements("title"))
  40. {
  41. Console.WriteLine(t.Value);
  42. }
  43. }
  44.  
  45. static void GroupOnGenre(XElement musicLibrary)
  46. {
  47. var groupQuery = from cd in musicLibrary.Elements("cd")
  48. group cd by cd.Element("genre").Value into genreGroup
  49. orderby genreGroup.Key
  50. select new
  51. {
  52. Genre = genreGroup.Key,Titles = from title in genreGroup.Elements("title")
  53. select title.Value
  54. };
  55. foreach (var entry in groupQuery)
  56. {
  57. Console.WriteLine("Genre: {0}",entry.Genre);
  58. Console.WriteLine("----------------");
  59. foreach (var title in entry.Titles)
  60. {
  61. Console.WriteLine("\t{0}",title);
  62. }
  63. Console.WriteLine();
  64. }
  65. }
运行结果如下:

3. 修改XML文档

  1. static void Main(string[] args)
  2. {
  3. XElement musicLibrary = XElement.Load(@"MusicLibrary.xml");
  4. Console.WriteLine("Adding a New CD\n===============");
  5. AddNewCD(musicLibrary);
  6. Console.WriteLine(musicLibrary);
  7. Console.WriteLine("\nRemoving a CD=============");
  8. RemoveCD(musicLibrary);
  9. Console.WriteLine(musicLibrary);
  10. Console.WriteLine("\nAdding a New CD Directly\n========================");
  11. AddNewCDDirectly(musicLibrary);
  12. Console.WriteLine(musicLibrary);
  13. Console.WriteLine("\nUpdate Year with ReplaceNodes\n=============================");
  14. UpdateYearWithReplaceNodes(musicLibrary);
  15. Console.WriteLine(musicLibrary);
  16. Console.WriteLine("\nUpdate Year with SetElementValue================================");
  17. UpdateYearWithSetElementValue(musicLibrary);
  18. Console.WriteLine(musicLibrary);
  19. Console.WriteLine("\nUpdate Attribute Value====================");
  20. UpdateAttributeValue(musicLibrary);
  21. Console.WriteLine(musicLibrary);
  22. Console.WriteLine("\nReplace CD Content==================");
  23. ReplaceCD(musicLibrary);
  24. Console.WriteLine(musicLibrary);
  25. Console.ReadLine();
  26. }
  27.  
  28. static void AddNewCD(XElement musicLibrary)
  29. {
  30. XElement cd = CreateCDElement("6","Back in Black",2003,"AC/DC","Rock");
  31. musicLibrary.Add(cd);
  32. }
  33.  
  34. static void AddNewCDDirectly(XElement musicLibrary)
  35. {
  36. musicLibrary.Add(
  37. new XElement("cd",6),"Back in Black"),2003),"AC/DC"),"Rock")));
  38. }
  39.  
  40. static void RemoveCD(XElement musicLibrary)
  41. {
  42. XElement cd = (from entry in musicLibrary.Elements("cd")
  43. where entry.Attribute("id").Value == "6"
  44. select entry).FirstOrDefault();
  45. if (null != cd)
  46. {
  47. cd.Remove();
  48. }
  49. }
  50.  
  51. static XElement CreateCDElement(string id,genre));
  52. }
  53.  
  54. static void UpdateYearWithReplaceNodes(XElement musicLibrary)
  55. {
  56. XElement cd = (from entry in musicLibrary.Elements("cd")
  57. where entry.Attribute("id").Value == "3"
  58. select entry).FirstOrDefault();
  59. cd.Element("year").ReplaceNodes("1986");
  60. }
  61.  
  62. static void UpdateYearWithSetElementValue(XElement musicLibrary)
  63. {
  64. XElement cd = (from entry in musicLibrary.Elements("cd")
  65. where entry.Attribute("id").Value == "3"
  66. select entry).FirstOrDefault();
  67. cd.SetElementValue("year","1987");
  68. }
  69.  
  70. static void UpdateAttributeValue(XElement musicLibrary)
  71. {
  72. XElement cd = (from entry in musicLibrary.Elements("cd")
  73. where entry.Attribute("id").Value == "3"
  74. select entry).FirstOrDefault();
  75. cd.SetAttributeValue("id","7");
  76. }
  77.  
  78. static void ReplaceCD(XElement musicLibrary)
  79. {
  80. XElement cd = (from entry in musicLibrary.Elements("cd")
  81. where entry.Attribute("id").Value == "1"
  82. select entry).FirstOrDefault();
  83.  
  84. cd.ReplaceWith( new XElement("cd",1),"Rock")));
  85. }

猜你在找的XML相关文章