1、向文件中写入XML

            XmlDocument xmlDoc = new XmlDocument();//在内存中构建一个Dom对象
            XmlDeclaration xmld = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");//指定文档声明
            xmlDoc.AppendChild(xmld);//将文档说明添加到文档中去

            XmlElement rootElement = xmlDoc.CreateElement("school");//创建一个根元素,school
            xmlDoc.AppendChild(rootElement);//将根元素加入进去

            XmlElement xmlClassElement = xmlDoc.CreateElement("class");//为根元素(school)添加子元素
            XmlAttribute attr = xmlDoc.CreateAttribute("id");//为class添加属性 id,
            attr.Value = "c01";//id的值为c01
            xmlClassElement.Attributes.Append(attr);//将属性添加到class标签中去。
            rootElement.AppendChild(xmlClassElement);//将class元素添加到school标签中去

            XmlElement xmlStudentElement = xmlDoc.CreateElement("student");//创建一个student元素
            attr = xmlDoc.CreateAttribute("sid");//创建一个名叫sid的属性
            attr.Value = "s011";//属性的值为s011
            xmlStudentElement.Attributes.Append(attr); //将属性添加到元素中去
            xmlClassElement.AppendChild(xmlStudentElement);//将student节点加到class节点中去

            XmlElement xmlNameElement = xmlDoc.CreateElement("name");
            xmlNameElement.InnerText = "james";
            XmlElement xmlAgeElement = xmlDoc.CreateElement("age");
            xmlAgeElement.InnerText = "18";
            xmlStudentElement.AppendChild(xmlNameElement);
            xmlStudentElement.AppendChild(xmlAgeElement);

            xmlDoc.Save("school.xml");//将该Dom对象写入到XML文件中
兼容.net 2.0版本

相关文章: