目录
一、加载、创建、保存、遍历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.运行效果
.NET 7.控制台应用,需要NuGet相关的程序包,其安装方法详见作者此前发布的文章。
// LINQ to XML 编程:加载 xml、创建全新 xml、保存xml
using System.IO;
using System.Xml.Linq;
namespace _10_3
{
class Program
{
static void Main(string[] args)
{
//加载已有XML
LoadFromFile();
Console.WriteLine("------------------------------------------------------------");
LoadFromString();
Console.WriteLine("------------------------------------------------------------");
//创建全新XML
CreateXml();
Console.WriteLine("------------------------------------------------------------");
//遍历XML
EnumXml();
Console.WriteLine("------------------------------------------------------------");
}
#region 从文件加载
///
/// Load()方法从文件加载XML
/// path文件路径
///
static void LoadFromFile()
{
string path = Directory.GetCurrentDirectory() + @"\LoadFromFile.xml";
XElement root = XElement.Load(path);
Console.WriteLine(root.ToString());
}
#endregion 从文件加载
#region 从string()加载并存储
///
/// Parse()方法从描述XML文件的一系列字符串加载
/// Save()存储XML文件
///
static void LoadFromString()
{
string path = Directory.GetCurrentDirectory() + @"\LoadFromStr.xml";
XElement root = XElement.Parse(@"
YGBH0001
小王
1500
YGBH0002
小李
3000
YGBH0003
小刘留
5000
");
Console.WriteLine(root.ToString());
root.Save(path);
}
#endregion 从string()加载并存储
#region 创建并存储XML
///
/// XElement()方法创建记录和元素
///
static void CreateXml()
{
string path = Directory.GetCurrentDirectory() + @"\CreateXml.xml";
XElement root = new("Categories",
new XElement("Category",
new XElement("CategoryID", Guid.NewGuid()),
new XElement("CategoryName", "食品"),
new XElement("Description", "可以吃的东西")
)
);
Console.WriteLine(root.ToString());
root.Save(path);
}
#endregion 创建并存储XML
#region 遍历XML
///
/// 如何遍历 xml 树,并获取指定元素
/// 遍历永远离不开foreach()的
///
static void EnumXml()
{
string path = Directory.GetCurrentDirectory() + @"\EnumXml.xml";
string strCon = "Data Source=DESKTOP-3LV13FS;Integrated Security=True;Database=db_CSharp;";
DataClasses1DataContext? _Linq;
_Linq = new DataClasses1DataContext(strCon);
XElement root = new("tb_Employee");
root.Add(_Linq.tb_Employee.Select(c => new XElement("ID",
new XElement("Name", c.Name)))
);
foreach (XElement? item in root.Elements("ID"))
{
if (item != null)
{
Console.WriteLine(item.Element("Name")!.Value); //“!”解除CS8602,关闭编译器空检查
}
}
root.Save(path);
}
#endregion 遍历XML
}
}
YGBH0001
小王
1500
3000
5000
YGBH0002
小李
1500
3000
5000
YGBH0003
小刘留
1500
3000
5000
------------------------------------------------------------
YGBH0001
小王
1500
YGBH0002
小李
3000
YGBH0003
小刘留
5000
------------------------------------------------------------
71b53e44-9e1b-43ce-b848-501b66e6493f
食品
可以吃的东西
------------------------------------------------------------
小王
小李
小刘留
小科
小亮
章子怡
汪峰
------------------------------------------------------------
方法 | 说明 |
AddAfterSelf | 紧跟在此节点之后添加指定的内容 |
AddBeforeSelf | 紧邻此节点之前添加指定的内容 |
方法 | 说明 |
ReplaceWith | 用指定的内容来取代当前元素的内容 |
ReplaceAll | 用指定的内容来取代当前元素的子节点及相关的属性 |
ReplaceNodes | 用指定的内容来取代文档或当前元素的子节点 |
SetAttributeValue | 设置属性的值、添加属性或移除属性 |
SetElementValue | 设置子元素的值、添加子元素或移除子元素 |
.NET 7.0控制台应用程序。
// LINQtoXML 修改xml树:添加、删除、更新xml文档的内容。
using System.IO;
using System.Xml.Linq;
namespace _10_4
{
class Program
{
#region 在此节点之后添加
///
/// 在此节点之后添加
///
static void AddAfterSelf()
{
string path = Directory.GetCurrentDirectory() + @"\AddAfterSelf.xml";
XElement? root = XElement.Parse(@"
1
Beverages
Soft drinks, coffees, teas, beers, and ales
");
XElement xele = root.Element("Category")!.Element("CategoryName")!; //!编译器禁止做null判断
xele.AddAfterSelf(new XElement("AddDate", DateTime.Now));
Console.WriteLine(root.ToString());
root.Save(path);
}
#endregion 在此节点之后添加
#region 在 LINQtoXML中更新xml
///
/// 更新xml
/// 使用了ReplaceWith与SetElementValue方法更新xml
///
static void Update()
{
string path = Directory.GetCurrentDirectory() + @"\Update.xml";
XElement? root = XElement.Parse(@"
1
Beverages
Soft drinks, coffees, teas, beers, and ales
");
root.Element("Category")!.Element("CategoryID")!.ReplaceWith(new XElement("ID", "2")); //修改1 →1
root.Element("Category")!.SetElementValue("CategoryName", "test data"); //修改Beverages→test data
Console.WriteLine(root.ToString());
root.Save(path);
}
#endregion 在 LINQtoXML中更新xml
#region 删除 xml
///
///
///
static void RemoveAll()
{
string path = Directory.GetCurrentDirectory() + @"\RemoveAll.xml";
XElement root = XElement.Parse(@"
1
Beverages
Soft drinks, coffees, teas, beers, and ales
");
root.RemoveAll();
Console.WriteLine(root.ToString());
root.Save(path);
}
#endregion 删除 xml
#region 删除元素
static void Remove()
{
string path = Directory.GetCurrentDirectory() + @"\Remove.xml";
XElement root = XElement.Parse(@"
1
Beverages
Soft drinks, coffees, teas, beers, and ales
");
root.Element("Category")!.Element("Description")!.Remove(); //删除元素Description
Console.WriteLine(root.ToString());
root.Save(path);
}
#endregion 删除元素
static void Main(string[] args)
{
//在此节点之后添加
AddAfterSelf();
Console.WriteLine("------------------------------------------------------------");
//在 LINQtoXML中更新xml
Update();
Console.WriteLine("------------------------------------------------------------");
//删除xml
RemoveAll();
Console.WriteLine("------------------------------------------------------------");
//删除元素
Remove();
Console.WriteLine("------------------------------------------------------------");
}
}
}
1
Beverages
2023-11-08T22:11:10.1486749+08:00
Soft drinks, coffees, teas, beers, and ales
------------------------------------------------------------
2
test data
Soft drinks, coffees, teas, beers, and ales
------------------------------------------------------------
------------------------------------------------------------
1
Beverages
------------------------------------------------------------
// LINQtoXML添加属性、检索属性和删除属性
using System.IO;
using System.Xml.Linq;
namespace _10_5
{
class Program
{
#region 添加属性
static void AddAttribute()
{
string path = Directory.GetCurrentDirectory() + @"\AddAttribute.xml";
XElement root = new("Categories",
new XElement("Category",
new XAttribute("CategoryID", "1"),
new XElement("CategoryName", "Beverages"),
new XElement("Description", "Soft drinks, coffees, teas, beers, and ales"))
);
root.Element("Category")!.Add(new XAttribute("AddDate", DateTime.Now.ToShortDateString())); //添加属性
Console.WriteLine(root);
root.Save(path);
}
#endregion 添加属性
#region 检索属性
static void SelectAttribute()
{
XElement root = new("Categories",
new XElement("Category",
new XAttribute("CategoryID", "1"),
new XElement("CategoryName", "Beverages"),
new XElement("Description", "Soft drinks, coffees, teas, beers, and ales"))
);
XAttribute xattr = root.Element("Category")!.Attribute("CategoryID")!; //检索指定元素
Console.WriteLine(xattr.Name);
Console.WriteLine(xattr.Value);
}
#endregion 检索属性
#region 删除属性
static void Remove()
{
string path = Directory.GetCurrentDirectory() + @"\RemoveAttri.xml";
XElement root = new("Categories",
new XElement("Category",
new XAttribute("CategoryID", "1"),
new XElement("CategoryName", "Beverages"),
new XElement("Description", "Soft drinks, coffees, teas, beers, and ales"))
);
root.Element("Category")!.Attribute("CategoryID")!.Remove(); //删除属性CategoryID
Console.WriteLine(root.ToString());
root.Save(path);
}
#endregion 删除属性
static void Main(string[] args)
{
//添加属性
AddAttribute();
Console.WriteLine("------------------------------------------------------------");
//检索属性
SelectAttribute();
Console.WriteLine("------------------------------------------------------------");
//删除属性
Remove();
Console.WriteLine("------------------------------------------------------------");
}
}
}
Beverages
Soft drinks, coffees, teas, beers, and ales
------------------------------------------------------------
CategoryID
1
------------------------------------------------------------
Beverages
Soft drinks, coffees, teas, beers, and ales
------------------------------------------------------------