两种方法,看大家喜好选择吧:
方法一:
XmlDocument xmldoc = new XmlDocument();
XmlText xmltext;
//声明
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
xmlnode.InnerText += " encoding=\"GB2312\"";
xmldoc.AppendChild(xmlnode);
//添加根节点
XmlElement xmlelementroot = xmldoc.CreateElement("", "Config", "");
//根节点包含节点文本时会造成XML文档结构的混乱
//xmltext = xmldoc.CreateTextNode("配置信息");
//xmlelementroot.AppendChild(xmltext);
xmldoc.AppendChild(xmlelementroot);
//添加一个元素
XmlElement xmlelement1 = xmldoc.CreateElement("", "DTL", "");
xmltext = xmldoc.CreateTextNode("2010-10-25");
xmlelement1.AppendChild(xmltext);
xmldoc.ChildNodes.Item(1).AppendChild(xmlelement1);
//添加另一个元素
XmlElement xmlelement2 = xmldoc.CreateElement("", "DTF", "");
xmltext = xmldoc.CreateTextNode("2011-02-10");
xmlelement2.AppendChild(xmltext);
xmldoc.ChildNodes.Item(1).AppendChild(xmlelement2);
//保存
xmldoc.Save(getPath());
方法二:
XmlTextWriter xmlwriter = new XmlTextWriter(getPath(), Encoding.Default);
xmlwriter.Formatting = Formatting.Indented;
xmlwriter.Indentation = 4;
xmlwriter.WriteStartDocument();
xmlwriter.WriteStartElement("", "Config", "");
xmlwriter.WriteStartElement("", "DTL", "");
xmlwriter.WriteString("2010-10-25");
xmlwriter.WriteEndElement();
xmlwriter.WriteStartElement("", "DTF", "");
xmlwriter.WriteString("2011-02-10");
xmlwriter.WriteEndElement();
xmlwriter.WriteEndElement();
xmlwriter.WriteEndDocument();
xmlwriter.Flush();
xmlwriter.Close();
上面两段代码中的getPath()是自定义的一个获取文件路径加名称的方法,请根据自己实际情况修改!
总的来说还是方法二比较容易理解,简单易用,也是我常用的方法!
希望对各位有所帮助!