C# xml文件的创建

在创建XML文件之前,需要先引用using System.Xml;命名空间。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace RepeatStudy
{
	static void Main(string[] args)
    {
    	Create();
    }
	
	public static void Create()
	{
		try
		{
			//先创建个xml文件对象
			XmlDocument doc = new XmlDocument();
			//这个是xml文件第一行的说明信息
            XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.AppendChild(xmlDeclaration);

            XmlElement root = doc.CreateElement("root");
            doc.AppendChild(root);
			//root的下一个节点
            XmlElement book = doc.CreateElement("book");
            //给book元素设置属性,用于描述book
            XmlAttribute attr = doc.CreateAttribute("Value");
            attr.Value = "历史文学";
            book.Attributes.Append(attr);
            root.AppendChild(book);

            XmlElement id = doc.CreateElement("ID");
            id.InnerText = "123";
            book.AppendChild(id);

            XmlElement name = doc.CreateElement("Name");
            name.InnerText = "明朝那些事";
            book.AppendChild(name);
			//文档一些设置
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = System.Text.Encoding.UTF8;
            settings.Indent = true;
            settings.IndentChars = "    ";
			//如果自己未指定路径,xml文件默认创建在bin目录下的debug目录里
            XmlWriter writer = XmlWriter.Create("data2.xml", settings);
            doc.Save(writer);
		}
	}
}
结果展示


<root>
	<book Value="历史文学">
		<ID>123ID>
		<Name>明朝那些事Name>
	book>
root>

你可能感兴趣的:(c#,xml)