C#写xml
作者:互联网
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace CreateXml
{
class Program
{
static void Main(string[] args)
{
Program app = new Program();
app.CreateXmlFile();
}
public void CreateXmlFile()
{
XmlDocument xmlDoc = new XmlDocument();
//创建类型声明节点
XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
xmlDoc.AppendChild(node);
//创建根节点
XmlNode root = xmlDoc.CreateElement("grades");
xmlDoc.AppendChild(root);
XmlNode node1 = xmlDoc.CreateNode(XmlNodeType.Element, "grade", null);
CreateNode(xmlDoc, node1, "id", "2019001");
CreateNode(xmlDoc, node1, "name", "张三");
CreateNode(xmlDoc, node1, "course", "机器学习");
CreateNode(xmlDoc, node1, "score", "85");
root.AppendChild(node1);
XmlNode node2 = xmlDoc.CreateNode(XmlNodeType.Element, "grade", null);
CreateNode(xmlDoc, node2, "id", "2019002");
CreateNode(xmlDoc, node2, "name", "李四");
CreateNode(xmlDoc, node2, "course", "操作系统");
CreateNode(xmlDoc, node2, "score", "90");
root.AppendChild(node2);
XmlNode node3 = xmlDoc.CreateNode(XmlNodeType.Element, "grade", null);
CreateNode(xmlDoc, node3, "id", "2019003");
CreateNode(xmlDoc, node3, "name", "王五");
CreateNode(xmlDoc, node3, "course", "数据结构");
CreateNode(xmlDoc, node3, "score", "95");
root.AppendChild(node3);
try
{
xmlDoc.Save(@"D:\XML\grades");
}
catch (Exception e)
{
//显示错误信息
Console.WriteLine(e.Message);
}
//Console.ReadLine();
}
/// <summary>
/// 创建节点
/// </summary>
/// <param name="xmldoc"></param> xml文档
/// <param name="parentnode"></param>父节点
/// <param name="name"></param> 节点名
/// <param name="value"></param> 节点值
///
public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
{
XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
node.InnerText = value;
parentNode.AppendChild(node);
}
}
}
标签:xml,AppendChild,C#,CreateNode,node1,node3,XmlNode,xmlDoc 来源: https://www.cnblogs.com/wxdmse/p/14524205.html