

//定义XMLDocument
XmlDocument xmlDocument = new XmlDocument();
//定义XML文档头文件
XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0","utf-8",null);
//增加XML文档头
xmlDocument.AppendChild(xmlDeclaration);
//定义XML的根
XmlElement xmlRoot = xmlDocument.CreateElement("userdata");
//添加根的属性
xmlRoot.SetAttribute("createuser","true");
//修改根属性的值
xmlRoot.GetAttributeNode("createuser").Value = "false";
//添加子节点并设置子节点属性
xmlDocument.AppendChild(xmlRoot);
XmlElement dataconnection = xmlDocument.CreateElement("dataconnection");
XmlElement server = xmlDocument.CreateElement("server");
server.InnerText = "localhost";
XmlElement uid = xmlDocument.CreateElement("uid");
uid.InnerText = "sa";
XmlElement pwd = xmlDocument.CreateElement("pwd");
xmlRoot.AppendChild(dataconnection);
dataconnection.AppendChild(server);
dataconnection.AppendChild(uid);
dataconnection.AppendChild(pwd);
//保存XML文档
xmlDocument.Save("book.xml");
//读取子节点server的值
XmlNode xnserver = xmlDocument.SelectSingleNode("userdata/dataconnection/server");
Console.WriteLine("node server's value is "+ xnserver.InnerText);
Console.ReadLine();
生成的XML代码如下:


<?xml version="1.0" encoding="utf-8"?>
<userdata createuser="false">
<dataConnection>
<server>localhost</server>
<uid>sa</uid>
<pwd />
</dataConnection>
</userdata>