温馨提示×

C#实用教程操作xml文件

c#
小云
93
2023-09-15 06:12:37
栏目: 编程语言

操作XML文件是C#编程中非常常见的任务之一。下面是一个简单的C#实用教程,演示如何使用C#读取、编辑和保存XML文件。

读取XML文件:

using System;
using System.Xml;
public class XMLReader
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
doc.Load("data.xml");
XmlNode root = doc.DocumentElement;
foreach (XmlNode node in root.ChildNodes)
{
string name = node["Name"].InnerText;
int age = int.Parse(node["Age"].InnerText);
Console.WriteLine("Name: {0}, Age: {1}", name, age);
}
}
}

编辑XML文件:

using System;
using System.Xml;
public class XMLEditor
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
doc.Load("data.xml");
XmlNode root = doc.DocumentElement;
XmlNode newNode = doc.CreateElement("Person");
XmlNode nameNode = doc.CreateElement("Name");
nameNode.InnerText = "John Doe";
newNode.AppendChild(nameNode);
XmlNode ageNode = doc.CreateElement("Age");
ageNode.InnerText = "30";
newNode.AppendChild(ageNode);
root.AppendChild(newNode);
doc.Save("data.xml");
}
}

保存XML文件:

using System;
using System.Xml;
public class XMLWriter
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
doc.Load("data.xml");
XmlNode root = doc.DocumentElement;
foreach (XmlNode node in root.ChildNodes)
{
int age = int.Parse(node["Age"].InnerText);
node["Age"].InnerText = (age + 1).ToString();
}
doc.Save("data.xml");
}
}

请注意,上述代码中的"data.xml"是XML文件的路径。在使用这些代码之前,请确保在相应的路径上存在一个有效的XML文件。

这只是一个简单的C#实用教程,用于演示如何操作XML文件。在实际的应用程序中,您可能需要更多的错误处理和数据验证机制。

0