C# XML编程全攻略:深度解析创建、读取、更新与删除操作
在C#中,XML文件常被用于存储配置数据、交换数据或作为轻量级的数据持久化方案。以下是关于C#中如何使用XML文件的详细说明,包括创建、读取、更新和删除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文件。每段代码都附有详尽的注释,以便您理解和应用到实际项目中。