C#保存数据到XML
要将数据保存到XML文件中,可以使用C#中的XmlWriter类或XmlDocument类。
使用XmlWriter类:
using System;
using System.Xml;
public class Program
{
public static void Main()
{
// 创建XmlWriterSettings对象,用于设置XML编写器的设置
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true; // 设置缩进
// 创建XmlWriter对象,并指定保存的文件路径
using (XmlWriter writer = XmlWriter.Create("data.xml", settings))
{
// 开始写入XML文档
writer.WriteStartDocument();
// 写入根元素
writer.WriteStartElement("Root");
// 写入子元素
writer.WriteElementString("Name", "John");
writer.WriteElementString("Age", "30");
writer.WriteElementString("City", "New York");
// 结束写入XML文档
writer.WriteEndElement();
writer.WriteEndDocument();
}
}
}
使用XmlDocument类:
using System;
using System.Xml;
public class Program
{
public static void Main()
{
// 创建XmlDocument对象
XmlDocument doc = new XmlDocument();
// 创建XML声明
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(declaration);
// 创建根元素
XmlElement rootElement = doc.CreateElement("Root");
doc.AppendChild(rootElement);
// 创建子元素
XmlElement nameElement = doc.CreateElement("Name");
nameElement.InnerText = "John";
rootElement.AppendChild(nameElement);
XmlElement ageElement = doc.CreateElement("Age");
ageElement.InnerText = "30";
rootElement.AppendChild(ageElement);
XmlElement cityElement = doc.CreateElement("City");
cityElement.InnerText = "New York";
rootElement.AppendChild(cityElement);
// 保存XML文件
doc.Save("data.xml");
}
}
这两种方法都可以将数据保存到XML文件中,选择使用哪种方法取决于你的偏好和具体需求
原文地址: https://www.cveoy.top/t/topic/iAOx 著作权归作者所有。请勿转载和采集!