在C#开发中,处理XML格式数据是很多场景下的常见需求,传统的XML DOM操作方式步骤繁琐,代码可读性较差。Linq to XML作为.NET框架中提供的轻量级XML处理方案,通过XElement类可以快速、直观地构建XML文档结构,大幅简化XML文件的创建流程。

XElement核心概念
XElement是Linq to XML中最常用的类,代表一个XML元素,它可以直接定义元素的名称、内容、属性以及子元素,通过嵌套组合就能构建出完整的XML文档结构。使用XElement创建XML不需要像传统方式那样先创建XmlDocument对象,再逐步添加节点,代码逻辑更符合开发者的直观思维。
基础XML文档创建示例
下面是最简单的XML文档创建示例,构建一个包含学生信息的基础XML文件:
using System;
using System.Xml.Linq;
class Program
{
static void Main()
{
// 创建根元素,同时添加两个子元素
XElement root = new XElement("Students",
new XElement("Student",
new XElement("Name", "张三"),
new XElement("Age", 20),
new XElement("Major", "计算机科学")
),
new XElement("Student",
new XElement("Name", "李四"),
new XElement("Age", 21),
new XElement("Major", "软件工程")
)
);
// 将XElement保存为XML文件
root.Save("students.xml");
Console.WriteLine("XML文件创建成功");
}
}
运行上述代码后,会在程序运行目录下生成students.xml文件,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<Students>
<Student>
<Name>张三</Name>
<Age>20</Age>
<Major>计算机科学</Major>
</Student>
<Student>
<Name>李四</Name>
<Age>21</Age>
<Major>软件工程</Major>
</Student>
</Students>
添加元素属性与命名空间
实际开发中经常需要给XML元素添加属性,或者处理带命名空间的XML文档,XElement同样支持这些操作:
using System;
using System.Xml.Linq;
class Program
{
static void Main()
{
// 定义XML命名空间
XNamespace ns = "http://www.ipipp.com/student";
// 创建带命名空间和属性的XML文档
XElement root = new XElement(ns + "Students",
new XAttribute("Version", "1.0"),
new XAttribute(XNamespace.Xmlns + "stu", ns),
new XElement(ns + "Student",
new XAttribute("Id", "1001"),
new XElement(ns + "Name", "张三"),
new XElement(ns + "Score", 95)
)
);
root.Save("students_with_attr.xml");
Console.WriteLine("带属性和命名空间的XML文件创建成功");
}
}
生成的XML文件内容包含命名空间和元素属性,符合更复杂的业务场景需求。
动态构建XML文档
如果XML内容来自动态数据集合,也可以通过循环的方式构建XElement结构:
using System;
using System.Collections.Generic;
using System.Xml.Linq;
class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
// 模拟动态数据集合
List<Student> students = new List<Student>
{
new Student { Id = 1, Name = "张三", Age = 20 },
new Student { Id = 2, Name = "李四", Age = 21 },
new Student { Id = 3, Name = "王五", Age = 22 }
};
// 动态构建XML元素
XElement root = new XElement("StudentList",
new XAttribute("Total", students.Count),
// 遍历集合生成子元素
from stu in students
select new XElement("Student",
new XAttribute("Id", stu.Id),
new XElement("Name", stu.Name),
new XElement("Age", stu.Age)
)
);
root.Save("dynamic_students.xml");
Console.WriteLine("动态数据生成的XML文件创建成功");
}
}
常见问题说明
- 保存XML文件时默认编码为UTF-8,如果需要指定其他编码,可以在Save方法中传入Stream并指定编码格式
- XElement的构造函数支持任意数量的子元素参数,嵌套层级没有限制,可以构建任意复杂度的XML结构
- 如果元素内容包含特殊字符,XElement会自动进行转义处理,不需要开发者手动处理
- 可以通过
XElement.Parse方法直接将XML字符串转换为XElement对象,方便处理已有的XML内容
通过上述示例可以看出,使用C# Linq to XML的XElement构建XML文档非常灵活,无论是简单的固定结构还是复杂的动态数据场景,都能用简洁的代码实现,相比传统XML操作方式效率更高,代码更易维护。
C#Linq_to_XMLXElementXML文档创建修改时间:2026-07-13 08:30:31