• C#中通过LINQtoXML加载、创建、保存、遍历XML和修改XML树


    目录

    一、加载、创建、保存、遍历XML

    1.加载XML

    (1)从已有文件加载XML

    (2)从字符串加载XML

    2.创建并保存XML

    3.遍历XML

    4.示例源码 

    5.运行 

    二、修改XML的树

    1.添加节点

    2.删除

    3.更新

    4.示例源码

    5.运行效果

    三、修改XML属性

    1.添加

    2.检索

    3.删除

    4.示例源码

    5.运行效果


            LINQtoXML编程包含:加载xml、创建全新xml、遍历xml和修改 xml树 的信息。

    一、加载、创建、保存、遍历XML

    1.加载XML

    (1)从已有文件加载XML

            使用LINQtoXML 加载 xml 可以从多种数据源获得,例如字符串、 XmlReader TextReader 或文件。
            从已有文件中加载xml 是最常见的xml文件操作。

    (2)从字符串加载XML

            也可以使用 Parse()  方法从一个字符串加载 xml。

    2.创建并保存XML

            调用XElement 对象的构造函数可以创建 xml 文档。
            使用 LINQtoXML 也可以 创建 xml 文档。

    3.遍历XML

            使用 LINQtoXML xml 树中遍历 xml 是相当简单的。只需要使用 XElement XAttribute 类中的方法。Elements 和 Element 方法提供了定位到某个或某些元素的方式。 

    4.示例源码 

             .NET 7.控制台应用,需要NuGet相关的程序包,其安装方法详见作者此前发布的文章。

    1. // LINQ to XML 编程:加载 xml、创建全新 xml、保存xml
    2. using System.IO;
    3. using System.Xml.Linq;
    4. namespace _10_3
    5. {
    6. class Program
    7. {
    8. static void Main(string[] args)
    9. {
    10. //加载已有XML
    11. LoadFromFile();
    12. Console.WriteLine("------------------------------------------------------------");
    13. LoadFromString();
    14. Console.WriteLine("------------------------------------------------------------");
    15. //创建全新XML
    16. CreateXml();
    17. Console.WriteLine("------------------------------------------------------------");
    18. //遍历XML
    19. EnumXml();
    20. Console.WriteLine("------------------------------------------------------------");
    21. }
    22. #region 从文件加载
    23. ///
    24. /// Load()方法从文件加载XML
    25. /// path文件路径
    26. ///
    27. static void LoadFromFile()
    28. {
    29. string path = Directory.GetCurrentDirectory() + @"\LoadFromFile.xml";
    30. XElement root = XElement.Load(path);
    31. Console.WriteLine(root.ToString());
    32. }
    33. #endregion 从文件加载
    34. #region 从string()加载并存储
    35. ///
    36. /// Parse()方法从描述XML文件的一系列字符串加载
    37. /// Save()存储XML文件
    38. ///
    39. static void LoadFromString()
    40. {
    41. string path = Directory.GetCurrentDirectory() + @"\LoadFromStr.xml";
    42. XElement root = XElement.Parse(@"
    43. YGBH0001
    44. 小王
    45. 1500
    46. YGBH0002
    47. 小李
    48. 3000
    49. YGBH0003
    50. 小刘留
    51. 5000
    52. ");
    53. Console.WriteLine(root.ToString());
    54. root.Save(path);
    55. }
    56. #endregion 从string()加载并存储
    57. #region 创建并存储XML
    58. ///
    59. /// XElement()方法创建记录和元素
    60. ///
    61. static void CreateXml()
    62. {
    63. string path = Directory.GetCurrentDirectory() + @"\CreateXml.xml";
    64. XElement root = new("Categories",
    65. new XElement("Category",
    66. new XElement("CategoryID", Guid.NewGuid()),
    67. new XElement("CategoryName", "食品"),
    68. new XElement("Description", "可以吃的东西")
    69. )
    70. );
    71. Console.WriteLine(root.ToString());
    72. root.Save(path);
    73. }
    74. #endregion 创建并存储XML
    75. #region 遍历XML
    76. ///
    77. /// 如何遍历 xml 树,并获取指定元素
    78. /// 遍历永远离不开foreach()的
    79. ///
    80. static void EnumXml()
    81. {
    82. string path = Directory.GetCurrentDirectory() + @"\EnumXml.xml";
    83. string strCon = "Data Source=DESKTOP-3LV13FS;Integrated Security=True;Database=db_CSharp;";
    84. DataClasses1DataContext? _Linq;
    85. _Linq = new DataClasses1DataContext(strCon);
    86. XElement root = new("tb_Employee");
    87. root.Add(_Linq.tb_Employee.Select(c => new XElement("ID",
    88. new XElement("Name", c.Name)))
    89. );
    90. foreach (XElement? item in root.Elements("ID"))
    91. {
    92. if (item != null)
    93. {
    94. Console.WriteLine(item.Element("Name")!.Value); //“!”解除CS8602,关闭编译器空检查
    95. }
    96. }
    97. root.Save(path);
    98. }
    99. #endregion 遍历XML
    100. }
    101. }

    5.运行 

    1. YGBH0001
    2. 小王
    3. 1500
    4. 3000
    5. 5000
    6. YGBH0002
    7. 小李
    8. 1500
    9. 3000
    10. 5000
    11. YGBH0003
    12. 小刘留
    13. 1500
    14. 3000
    15. 5000
    16. ------------------------------------------------------------
    17. YGBH0001
    18. 小王
    19. 1500
    20. YGBH0002
    21. 小李
    22. 3000
    23. YGBH0003
    24. 小刘留
    25. 5000
    26. ------------------------------------------------------------
    27. 71b53e44-9e1b-43ce-b848-501b66e6493f
    28. 食品
    29. 可以吃的东西
    30. ------------------------------------------------------------
    31. 小王
    32. 小李
    33. 小刘留
    34. 小科
    35. 小亮
    36. 章子怡
    37. 汪峰
    38. ------------------------------------------------------------

    二、修改XML的树

            LINQtoXML 一个重要的特性是能够方便地修改 xml 树,如 添加、删除、更新 xml 文档的内容。

    1.添加节点

            使用 XNode 类的插入方法可以方便地向 xml 树添加内容。
    方法说明
    AddAfterSelf紧跟在此节点之后添加指定的内容
    AddBeforeSelf紧邻此节点之前添加指定的内容

    2.删除

            使用 Remove(XElement)方法来删除元素 ,使用  RemoveAll 方法来删除 xml

    3.更新

            在 LINQtoXML 中更新xml内容可以使用以下几种方法:                
    方法说明
    ReplaceWith用指定的内容来取代当前元素的内容
    ReplaceAll用指定的内容来取代当前元素的子节点及相关的属性
    ReplaceNodes用指定的内容来取代文档或当前元素的子节点
    SetAttributeValue设置属性的值、添加属性或移除属性
    SetElementValue设置子元素的值、添加子元素或移除子元素

    4.示例源码

            .NET 7.0控制台应用程序。

    1. // LINQtoXML 修改xml树:添加、删除、更新xml文档的内容。
    2. using System.IO;
    3. using System.Xml.Linq;
    4. namespace _10_4
    5. {
    6. class Program
    7. {
    8. #region 在此节点之后添加
    9. ///
    10. /// 在此节点之后添加
    11. ///
    12. static void AddAfterSelf()
    13. {
    14. string path = Directory.GetCurrentDirectory() + @"\AddAfterSelf.xml";
    15. XElement? root = XElement.Parse(@"
    16. 1
    17. Beverages
    18. Soft drinks, coffees, teas, beers, and ales
    19. ");
    20. XElement xele = root.Element("Category")!.Element("CategoryName")!; //!编译器禁止做null判断
    21. xele.AddAfterSelf(new XElement("AddDate", DateTime.Now));
    22. Console.WriteLine(root.ToString());
    23. root.Save(path);
    24. }
    25. #endregion 在此节点之后添加
    26. #region 在 LINQtoXML中更新xml
    27. ///
    28. /// 更新xml
    29. /// 使用了ReplaceWith与SetElementValue方法更新xml
    30. ///
    31. static void Update()
    32. {
    33. string path = Directory.GetCurrentDirectory() + @"\Update.xml";
    34. XElement? root = XElement.Parse(@"
    35. 1
    36. Beverages
    37. Soft drinks, coffees, teas, beers, and ales
    38. ");
    39. root.Element("Category")!.Element("CategoryID")!.ReplaceWith(new XElement("ID", "2")); //修改11
    40. root.Element("Category")!.SetElementValue("CategoryName", "test data"); //修改Beverages→test data
    41. Console.WriteLine(root.ToString());
    42. root.Save(path);
    43. }
    44. #endregion 在 LINQtoXML中更新xml
    45. #region 删除 xml
    46. ///
    47. ///
    48. ///
    49. static void RemoveAll()
    50. {
    51. string path = Directory.GetCurrentDirectory() + @"\RemoveAll.xml";
    52. XElement root = XElement.Parse(@"
    53. 1
    54. Beverages
    55. Soft drinks, coffees, teas, beers, and ales
    56. ");
    57. root.RemoveAll();
    58. Console.WriteLine(root.ToString());
    59. root.Save(path);
    60. }
    61. #endregion 删除 xml
    62. #region 删除元素
    63. static void Remove()
    64. {
    65. string path = Directory.GetCurrentDirectory() + @"\Remove.xml";
    66. XElement root = XElement.Parse(@"
    67. 1
    68. Beverages
    69. Soft drinks, coffees, teas, beers, and ales
    70. ");
    71. root.Element("Category")!.Element("Description")!.Remove(); //删除元素Description
    72. Console.WriteLine(root.ToString());
    73. root.Save(path);
    74. }
    75. #endregion 删除元素
    76. static void Main(string[] args)
    77. {
    78. //在此节点之后添加
    79. AddAfterSelf();
    80. Console.WriteLine("------------------------------------------------------------");
    81. //在 LINQtoXML中更新xml
    82. Update();
    83. Console.WriteLine("------------------------------------------------------------");
    84. //删除xml
    85. RemoveAll();
    86. Console.WriteLine("------------------------------------------------------------");
    87. //删除元素
    88. Remove();
    89. Console.WriteLine("------------------------------------------------------------");
    90. }
    91. }
    92. }

    5.运行效果

    1. 1
    2. Beverages
    3. 2023-11-08T22:11:10.1486749+08:00
    4. Soft drinks, coffees, teas, beers, and ales
    5. ------------------------------------------------------------
    6. 2
    7. test data
    8. Soft drinks, coffees, teas, beers, and ales
    9. ------------------------------------------------------------
    10. ------------------------------------------------------------
    11. 1
    12. Beverages
    13. ------------------------------------------------------------

    三、修改XML属性

    1.添加

            LINQtoXML添加属性与添加元素是类似的,可以使用构造函数或者 Add() 方法来添加属性。

    2.检索

            检索属性可以使用 Attribute(name) 方法查找指定的元素。

    3.删除

            调用 XAttribute 对象的 Remove 方法来完成删除属性的操作。

    4.示例源码

    1. // LINQtoXML添加属性、检索属性和删除属性
    2. using System.IO;
    3. using System.Xml.Linq;
    4. namespace _10_5
    5. {
    6. class Program
    7. {
    8. #region 添加属性
    9. static void AddAttribute()
    10. {
    11. string path = Directory.GetCurrentDirectory() + @"\AddAttribute.xml";
    12. XElement root = new("Categories",
    13. new XElement("Category",
    14. new XAttribute("CategoryID", "1"),
    15. new XElement("CategoryName", "Beverages"),
    16. new XElement("Description", "Soft drinks, coffees, teas, beers, and ales"))
    17. );
    18. root.Element("Category")!.Add(new XAttribute("AddDate", DateTime.Now.ToShortDateString())); //添加属性
    19. Console.WriteLine(root);
    20. root.Save(path);
    21. }
    22. #endregion 添加属性
    23. #region 检索属性
    24. static void SelectAttribute()
    25. {
    26. XElement root = new("Categories",
    27. new XElement("Category",
    28. new XAttribute("CategoryID", "1"),
    29. new XElement("CategoryName", "Beverages"),
    30. new XElement("Description", "Soft drinks, coffees, teas, beers, and ales"))
    31. );
    32. XAttribute xattr = root.Element("Category")!.Attribute("CategoryID")!; //检索指定元素
    33. Console.WriteLine(xattr.Name);
    34. Console.WriteLine(xattr.Value);
    35. }
    36. #endregion 检索属性
    37. #region 删除属性
    38. static void Remove()
    39. {
    40. string path = Directory.GetCurrentDirectory() + @"\RemoveAttri.xml";
    41. XElement root = new("Categories",
    42. new XElement("Category",
    43. new XAttribute("CategoryID", "1"),
    44. new XElement("CategoryName", "Beverages"),
    45. new XElement("Description", "Soft drinks, coffees, teas, beers, and ales"))
    46. );
    47. root.Element("Category")!.Attribute("CategoryID")!.Remove(); //删除属性CategoryID
    48. Console.WriteLine(root.ToString());
    49. root.Save(path);
    50. }
    51. #endregion 删除属性
    52. static void Main(string[] args)
    53. {
    54. //添加属性
    55. AddAttribute();
    56. Console.WriteLine("------------------------------------------------------------");
    57. //检索属性
    58. SelectAttribute();
    59. Console.WriteLine("------------------------------------------------------------");
    60. //删除属性
    61. Remove();
    62. Console.WriteLine("------------------------------------------------------------");
    63. }
    64. }
    65. }

    5.运行效果

    1. "1" AddDate="2023-11-08">
    2. Beverages
    3. Soft drinks, coffees, teas, beers, and ales
    4. ------------------------------------------------------------
    5. CategoryID
    6. 1
    7. ------------------------------------------------------------
    8. Beverages
    9. Soft drinks, coffees, teas, beers, and ales
    10. ------------------------------------------------------------

  • 相关阅读:
    TrueTouch学习记录
    【MHA】MySQL高可用MHA介绍2-安装,配置,要求与限制
    【计算机网络】IO多路转接之poll
    爬虫从入门到入牢
    医院安全(不良)事件上报系统源码 不良事件报告平台源码 前后端分离,支持二开
    [PyTorch][chapter 62][强化学习-基本概念]
    Day37-Http、Maven
    02_Docker
    LabVIEW软件开发工程师需要具备哪些能力与素质?
    java计算机毕业设计红河旅游信息服务系统源码+数据库+系统+lw文档+mybatis+运行部署
  • 原文地址:https://blog.csdn.net/wenchm/article/details/134220581