1.创建简单的XML文件
为了便于测试,我们首先创建控制台应用程序,项目命名为CreateXml,Program.cs代码如下:
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("User");
xmlDoc.AppendChild(root);
CreateNode(xmlDoc, root, "name", "xuwei");
CreateNode(xmlDoc, root, "sex", "male");
CreateNode(xmlDoc, root, "age", "25");
try
{
xmlDoc.Save("c://data2.xml");
}
catch (Exception e)
{
//显示错误信息
Console.WriteLine(e.Message);
}
//Console.ReadLine();
}
///
/// 创建节点
///
/// xml文档
/// 父节点
/// 节点名
/// 节点值
///
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);
}
}
}
XmlNode node2 = xmlDoc.CreateNode(XmlNodeType.Element, "User", null);
CreateNode(xmlDoc, node2, "name", "xiaolai");
CreateNode(xmlDoc, node2, "sex", "female");
CreateNode(xmlDoc, node2, "age", "23");
root.AppendChild(node2);
try
{
xmlDoc.Save("c://data5.xml");
}
catch (Exception e)
{
//显示错误信息
Console.WriteLine(e.Message);
}
//Console.ReadLine();
}