C# XML编程全攻略:深度解析创建、读取、更新与删除操作

2024-06-08 1158阅读

在C#中,XML文件常被用于存储配置数据、交换数据或作为轻量级的数据持久化方案。以下是关于C#中如何使用XML文件的详细说明,包括创建、读取、更新和删除XML数据的代码示例,以及详尽的注释解释。

C# XML编程全攻略:深度解析创建、读取、更新与删除操作
(图片来源网络,侵删)

1. 创建XML文件

使用XmlDocument创建
 

Csharp

using System;
using System.Xml;
namespace CSharpXMLExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建一个新的XML文档对象
            XmlDocument xmlDoc = new XmlDocument();
            // 创建XML声明
            XmlDeclaration xmlDecl = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmlDoc.AppendChild(xmlDecl);
            // 创建根元素
            XmlElement rootElement = xmlDoc.CreateElement("Root");
            xmlDoc.AppendChild(rootElement);
            // 在根元素下创建子元素并设置属性
            XmlElement childElement = xmlDoc.CreateElement("Child");
            childElement.SetAttribute("attributeName", "AttributeValue");
            childElement.InnerText = "Element Text";
            rootElement.AppendChild(childElement);
            // 保存到文件
            xmlDoc.Save("example.xml");
            Console.WriteLine("XML file created successfully.");
        }
    }
}

注释:

  • XmlDocument是.NET框架中用于表示整个XML文档的对象。
  • CreateXmlDeclaration用于创建XML声明,指定版本、编码和独立性。
  • CreateElement用于创建XML元素,可以设置其名称。
  • SetAttribute用于给元素添加属性。
  • InnerText用于设置元素的文本内容。
  • AppendChild用于将元素添加到父元素下。
  • 最后使用Save方法将XML文档保存到指定文件。
    使用XElement(LINQ to XML)创建
     
    

    Csharp

    using System;
    using System.Xml.Linq;
    namespace CSharpXMLExample
    {
        class Program
        {
            static void Main(string[] args)
            {
                // 使用LINQ to XML创建XML文档
                XElement root = new XElement("Root",
                    new XElement("Child",
                        new XAttribute("attributeName", "AttributeValue"),
                        "Element Text"));
                // 保存到文件
                root.Save("example.xml");
                Console.WriteLine("XML file created successfully using LINQ to XML.");
            }
        }
    }

    注释:

    • XElement是LINQ to XML中用于表示XML元素的对象,创建时直接指定元素名及子元素或文本内容。
    • XAttribute用于创建XML属性,与对应的元素一起构造。
    • 使用Save方法将XElement作为根元素保存到文件。

      2. 读取XML文件

      使用XmlDocument读取
       
      

      Csharp

      using System;
      using System.Xml;
      namespace CSharpXMLExample
      {
          class Program
          {
              static void Main(string[] args)
              {
                  XmlDocument xmlDoc = new XmlDocument();
                  xmlDoc.Load("example.xml");
                  // 获取根元素
                  XmlElement rootElement = xmlDoc.DocumentElement;
                  // 遍历子元素
                  foreach (XmlElement child in rootElement.ChildNodes)
                  {
                      Console.WriteLine($"Element Name: {child.Name}");
                      Console.WriteLine($"Attribute Value: {child.GetAttribute("attributeName")}");
                      Console.WriteLine($"Element Text: {child.InnerText}");
                      Console.WriteLine();
                  }
              }
          }
      }

      注释:

      • Load方法用于从文件加载XML文档。
      • DocumentElement属性返回XML文档的根元素。
      • ChildNodes属性包含根元素的所有子节点,遍历这些节点并打印元素名称、属性值和文本内容。
        使用XDocument(LINQ to XML)读取
         
        

        Csharp

        using System;
        using System.Xml.Linq;
        namespace CSharpXMLExample
        {
            class Program
            {
                static void Main(string[] args)
                {
                    XDocument doc = XDocument.Load("example.xml");
                    // 查询XML文档,提取所需信息
                    var children = from child in doc.Root.Elements("Child")
                                   select new
                                   {
                                       ElementName = child.Name.LocalName,
                                       AttributeValue = child.Attribute("attributeName").Value,
                                       TextContent = child.Value
                                   };
                    foreach (var child in children)
                    {
                        Console.WriteLine($"Element Name: {child.ElementName}");
                        Console.WriteLine($"Attribute Value: {child.AttributeValue}");
                        Console.WriteLine($"Element Text: {child.TextContent}");
                        Console.WriteLine();
                    }
                }
            }
        }

        注释:

        • XDocument是LINQ to XML中表示整个XML文档的对象,使用Load方法加载文件。
        • Elements方法用于获取根元素下的所有指定名称的子元素。
        • 使用LINQ查询表达式提取元素名称、属性值和文本内容,并循环打印。

          3. 更新XML文件

          使用XmlDocument更新
           
          

          Csharp

          using System;
          using System.Xml;
          namespace CSharpXMLExample
          {
              class Program
              {
                  static void Main(string[] args)
                  {
                      XmlDocument xmlDoc = new XmlDocument();
                      xmlDoc.Load("example.xml");
                      // 查找要更新的元素
                      XmlNode targetNode = xmlDoc.SelectSingleNode("//Child[@attributeName='AttributeValue']");
                      if (targetNode != null)
                      {
                          // 更新属性值
                          targetNode.Attributes["attributeName"].Value = "NewAttributeValue";
                          targetNode.InnerText = "Updated Text";
                          // 保存更改到文件
                          xmlDoc.Save("example.xml");
                          Console.WriteLine("XML file updated successfully.");
                      }
                      else
                      {
                          Console.WriteLine("Target element not found.");
                      }
                  }
              }
          }

          注释:

          • 使用SelectSingleNode方法通过XPath表达式定位要更新的元素。
          • 直接修改找到的元素的属性值和文本内容。
          • 保存更改到文件。
            使用XDocument(LINQ to XML)更新
             
            

            Csharp

            using System;
            using System.Xml.Linq;
            namespace CSharpXMLExample
            {
                class Program
                {
                    static void Main(string[] args)
                    {
                        XDocument doc = XDocument.Load("example.xml");
                        // 查询并更新元素
                        var child = doc.Descendants("Child")
                                       .FirstOrDefault(c => (string)c.Attribute("attributeName") == "AttributeValue");
                        if (child != null)
                        {
                            child.SetAttributeValue("attributeName", "NewAttributeValue");
                            child.Value = "Updated Text";
                            doc.Save("example.xml");
                            Console.WriteLine("XML file updated successfully using LINQ to XML.");
                        }
                        else
                        {
                            Console.WriteLine("Target element not found.");
                        }
                    }
                }
            }

            注释:

            • 使用Descendants方法查找所有名为“Child”的后代元素,并通过LINQ条件筛选出目标元素。
            • 使用SetAttributeValue方法更新属性值。
            • 直接修改元素的Value属性以更新文本内容。
            • 保存更改到文件。

              4. 删除XML文件中的元素

              使用XmlDocument删除
               
              

              Csharp

                  using System;
              using System.Xml;
              namespace CSharpXMLExample
              {
                  class Program
                  {
                      static void Main(string[] args)
                      {
                          XmlDocument xmlDoc = new XmlDocument();
                          xmlDoc.Load("example.xml");
                          // 查找并删除元素
                          XmlNode targetNode = xmlDoc.SelectSingleNode("//Child[@attributeName='AttributeValue']");
                          if (targetNode != null)
                          {
                              targetNode.ParentNode.RemoveChild(targetNode);
                              // 保存更改到文件
                              xmlDoc.Save("example.xml");
                              Console.WriteLine("XML file updated successfully (element deleted).");
                          }
                          else
                          {
                              Console.WriteLine("Target element not found.");
                          }
                      }
                  }
              }

              注释:

              • 使用SelectSingleNode方法通过XPath表达式定位要删除的元素。
              • 调用RemoveChild方法从其父节点移除该元素。
              • 保存更改到文件。
                使用XDocument(LINQ to XML)删除
                 
                

                Csharp

                using System;
                using System.Xml.Linq;
                namespace CSharpXMLExample
                {
                    class Program
                    {
                        static void Main(string[] args)
                        {
                            XDocument doc = XDocument.Load("example.xml");
                            // 查询并删除元素
                            var childToRemove = doc.Descendants("Child")
                                                   .FirstOrDefault(c => (string)c.Attribute("attributeName") == "AttributeValue");
                            if (childToRemove != null)
                            {
                                childToRemove.Remove();
                                doc.Save("example.xml");
                                Console.WriteLine("XML file updated successfully (element deleted) using LINQ to XML.");
                            }
                            else
                            {
                                Console.WriteLine("Target element not found.");
                            }
                        }
                    }
                }

                注释:

                • 使用Descendants方法查找所有名为“Child”的后代元素,并通过LINQ条件筛选出目标元素。
                • 直接调用Remove方法删除找到的元素。
                • 保存更改到文件。

                  以上代码示例详细展示了如何在C#中使用XmlDocument和XDocument(LINQ to XML)来创建、读取、更新和删除XML文件。每段代码都附有详尽的注释,以便您理解和应用到实际项目中。

VPS购买请点击我

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

目录[+]