XML学习笔记

一,XML规范

复制代码
1 <?xml version="1.0" encoding="utf-8"?>
2 <Contacts><!--注释-->
3   <Contact id="01">
4     <Name>Daisy Abbey</Name>
5     <Gender>female</Gender>
6   </Contact>
7 </Contacts>

第一行是XML文档的声明,主要由两个部分组成:
   version:文档符合XML1.0规范。
   encoding:文档字符编码,默认为"UTF-8"

注释:使用<!--内容-->格式,无法被嵌套
标签:自定义的,包括属性
注意:XML是一种标记语言,严格区分大小写,必须成对出现,注意结尾的反斜杠
------------------------------------------------------------------------------------------------------------------------------------------------------------- 版权声明:本文为CSDN博主「『泽』」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/qq_42766492/article/details/82314947
复制代码

二,C#创建XML文件

1.使用XmlDocument.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
1.使用XmlDocument.
 
       使用XmlDocument是一种基于文档结构模型的方式来读取XML文件.在XML文件中,我们可以把XML看作是由文档声明(Declare),元素(Element),属性(Attribute),文本(Text)等构成的一个树.最开始的一个结点叫作根结点,每个结点都可以有自己的子结点.得到一个结点后,可以通过一系列属性或方法得到这个结点的值或其它的一些属性.例如:
   1: xn 代表一个结点
   2: xn.Name;  //这个结点的名称
   3: xn.Value;  //这个结点的值
   4: xn.ChildNodes;  //这个结点的所有子结点
   5: xn.ParentNode;  //这个结点的父结点
   6: .......
1.1 读取所有的数据.
使用的时候,首先声明一个XmlDocument对象,然后调用Load方法,从指定的路径加载XML文件.
   1: XmlDocument doc =   new XmlDocument();
   2: doc.Load(  @"..\..\Book.xml" );
     然后可以通过调用SelectSingleNode得到指定的结点,通过GetAttribute得到具体的属性值.

  例子:

复制代码
 1         /// <summary>
 2         /// 添加XML文件
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btn_AddXMLFolder_Click(object sender, EventArgs e)
 7         {
 8             // 在内存中创建XmlDocument对象
 9             XmlDocument document = new XmlDocument();
10             // 增加文档说明
11             XmlDeclaration declaration = document.CreateXmlDeclaration("1.0", "UTF-8", "");//xml文档的声明部分
12             // 添加至XmlDocument对象中
13             document.AppendChild(declaration);
14 
15             // 赋值
16             User user = new User() { ID = 1, Name ="张三", Sex = true, Age = "16岁" };
17             // 创建根节点User
18             XmlElement hUser = document.CreateElement("User");//CreateElement(节点名称)
19             // 设置根节点的属性
20             hUser.SetAttribute("Type", "员工");
21             // 创建子节点ID
22             XmlElement ID = document.CreateElement("ID");
23             ID.InnerText = user.ID.ToString(); //设置其值
24             XmlElement Name = document.CreateElement("Name");
25             Name.InnerText = user.Name;
26             XmlElement Sex = document.CreateElement("Sex");
27             Sex.InnerText = (user.Sex== true)? "":"";
28             XmlElement Age = document.CreateElement("Age");
29             Age.InnerText = user.Age;
30             // 添加至父节点User中
31             hUser.AppendChild(ID);
32             hUser.AppendChild(Name);
33             hUser.AppendChild(Sex);
34             hUser.AppendChild(Age);
35             // 将根节点添加至XML文档中
36             document.AppendChild(hUser);
37 
38             // 保存输出路径
39             document.Save(@"C:\folder\XMLFile1.xml");
40         }
41         /// <summary>
42         /// User信息类
43         /// </summary>
44         public class User
45         {
46             // ID
47             public int ID { get; set; }
48             // 姓名
49             public string Name { get; set; }
50             // 性别
51             public bool Sex { get; set; }
52             // 年龄
53             public string Age { get; set; }
54         }
View Code
复制代码

2.使用Linq to XML.-XElement

   Linq是C#3.0中出现的一个新特性,使用它可以方便的操作许多数据源,也包括XML文件.使用Linq操作XML文件非常的方便,而且也比较简单。

2.1创建
复制代码
 1        /// <summary>
 2         /// 通过xdocument写入文件
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btn_addXmlfile_Click(object sender, EventArgs e)
 7         {
 8             // 通过xdocument写入文件
 9             List<Person> list = new List<Person>();
10             list.Add(new Person() { Name = "Sam", Age = 18 });
11             list.Add(new Person() { Name = "Penny", Age = 20 });
12             // 1、创建Dom对象。
13             XDocument xDoc = new XDocument();
14             XDeclaration xDec = new XDeclaration("1.0", "utf-8", null);
15             // 设置文档定义
16             xDoc.Declaration = xDec;
17             // 2、创建根节点
18             XElement rootElement = new XElement("List");
19             xDoc.Add(rootElement);
20             // 3、循环创建节点
21             for (int i = 0; i < list.Count; i++)
22             {
23                 XElement PersonElement = new XElement("Person");
24                 PersonElement.SetAttributeValue("id", (i + 1).ToString());
25 
26                 PersonElement.SetElementValue("Name", list[i].Name);
27                 PersonElement.SetElementValue("Age", list[i].Age);
28                 rootElement.Add(PersonElement);
29             }
30             xDoc.Save(@"C:\Users\zhang-sh\source\repos\repo\repo\folder\List.xml");
31         }
32         /// <summary>
33         /// Person类
34         /// </summary>
35         public class Person
36         {
37             public string Name { get; set; }
38             public int Age { get; set; }
39         }
View Code
复制代码
2.2读取
复制代码
 1         /// <summary>
 2         /// 读取方法一 XDocument
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btn_Read_Click(object sender, EventArgs e)
 7         {
 8             // 加载xml文件
 9             XDocument xDocument = XDocument.Load(@"C:\Users\zhang-sh\source\repos\repo\repo\folder\XMLFile1.xml");  //从指定的位置加载xml文档  System.Environment.CurrentDirectory默认路径bin-debug下
10             // 获取根节点
11             XElement xElement= xDocument.Root;  //xDocument.Root获取文档的跟XElement
12 
13             System.Diagnostics.Debug.WriteLine("ID:"+xElement.Element("ID").Value);
14             System.Diagnostics.Debug.WriteLine("Name:" + xElement.Element("Name").Value);
15             System.Diagnostics.Debug.WriteLine("Sex:" + xElement.Element("Sex").Value);
16             System.Diagnostics.Debug.WriteLine("Age:" + xElement.Element("Age").Value);
17         }
View Code
复制代码

3.使用XmlTextReader和XmlTextWriter

3.1使用XmlTextReader读取数据的时候,首先创建一个流,然后用read()方法来不断的向下读,根据读取的结点的类型来进行相应的操作.
复制代码
 1     /// <summary>
 2         /// 读取方法二 XmlTextReader(文档流的读取方式,只读)
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void btn_ReadXML2_Click(object sender, EventArgs e)
 7         {
 8             // 读取文件
 9             XmlTextReader reader = new XmlTextReader(@"C:\Users\zhang-sh\source\repos\repo\repo\folder\XMLFile1.xml"); // System.Environment.CurrentDirectory默认路径bin - debug下
10 
11             while (reader.Read())
12             {
13                 if (reader.Name == "ID") //判断节点名称
14                 {
15                     System.Diagnostics.Debug.WriteLine(reader.ReadString()); // 读取节点内容
16                 }
17                 else if (reader.Name == "Name")
18                 {
19                     System.Diagnostics.Debug.WriteLine(reader.ReadString());
20                 }
21                 else if (reader.Name == "Sex")
22                 {
23                     System.Diagnostics.Debug.WriteLine(reader.ReadString());
24                 }
25                 else if (reader.Name == "Age")
26                 {
27                     System.Diagnostics.Debug.WriteLine(reader.ReadString());
28                 }
29             }
30             reader.Close();  //关闭文档流
31         }
View Code
复制代码
3.2XmlTextWriter

  XmlTextWriter写文件的时候,默认是覆盖以前的文件,如果此文件名不存在,它将创建此文件.首先设置一下,你要创建的XML文件格式。

1
2
3
      1: XmlTextWriter myXmlTextWriter =   new XmlTextWriter(  @"..\..\Book1.xml" ,   null );
      2:   //使用 Formatting 属性指定希望将 XML 设定为何种格式。 这样,子元素就可以通过使用 Indentation 和 IndentChar 属性来缩进。
      3: myXmlTextWriter.Formatting = Formatting.Indented;

三,C#-XML序列化Helper:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace WebServiceTest
{
    public class XMLSerializerHelper
    {
        /// <summary>
        /// 序列化对象
        /// </summary>
        /// <param name="t">对象类型</param>
        /// <returns></returns>
        public static string Serialize<T>(T t)
        {
            using (StringWriter sw = new StringWriter())
            {
                XmlSerializer xz = new XmlSerializer(typeof(T));
                xz.Serialize(sw, t);
                return sw.ToString();
            }
        }

        /// <summary>
        /// 反序列化为对象
        /// </summary>
        /// <param name="s">对象序列化后的Xml字符串</param>
        /// <returns></returns>
        public static T Deserialize<T>(string s) where T : class
        {
            using (StringReader sr = new StringReader(s))
            {
                XmlSerializer xz = new XmlSerializer(typeof(T));
                return xz.Deserialize(sr) as T;
            }
        }
    }

    #region 使用示例
    //序列化
    //Product product = new Product() { ProductID = 1, DisCount = 5 };
    //string s = UserQuery.SimpleSerializer.Serialize(product);
    //Console.WriteLine(s);

    ////反序列化
    //product = UserQuery.SimpleSerializer.Deserialize(typeof(UserQuery.Product), s);
    //Console.WriteLine(product.ProductID.ToString() + ", " + product.DisCount); //1, 5
    #endregion 使用示例
    #region 示例类
    /// <summary>
    /// 测试类
    /// </summary>
    [XmlRoot]
    public class Inventory
    {
        public Inventory() { }
        [XmlArray("allpro")]
        [XmlArrayItem("book", typeof(Book)),
         XmlArrayItem("prod", typeof(Product))]
        public Product[] InventroyItems { set; get; } = new Product[] { new Product(), new Product(), new Product() };  // 数组
    }

    public class Book : Product
    {
        public string ISBN { get; set; } = "测试ISBN";
    }

    /// <summary>
    /// 自定义节点名
    /// </summary>
    [Serializable]
    [XmlRoot("ProductLLL")]
    public class Product
    {
        [XmlAttribute("DiscountTitle")]
        public int DisCount { set; get; }

        public string ProductID { set; get; } = "ID123";  // 默认为[XmlElement("ProductID")] 
    }
    #endregion 示例类
}
/* 结果:
<?xml version="1.0" encoding="utf-16"?>
<Inventory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <allpro>
    <prod DiscountTitle="0">
      <ProductID>ID123</ProductID>
    </prod>
    <prod DiscountTitle="0">
      <ProductID>ID123</ProductID>
    </prod>
    <prod DiscountTitle="0">
      <ProductID>ID123</ProductID>
    </prod>
  </allpro>
</Inventory>*/

 详细见:C#三种常用的读取XML文件的方法

posted @   ꧁执笔小白꧂  阅读(176)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示