码迷,mamicode.com
首页 > Windows程序 > 详细

C# 操作XML

时间:2018-01-07 00:40:16      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:分享   color   ati   innertext   说明   图片   写入   code   root   

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版本

 

技术分享图片
            XDocument xDoc = new XDocument();//创建一个Dom对象
            XDeclaration xDeclaration = new XDeclaration("1.0", "utf-8", null);//声明文档类型
            xDoc.Declaration = xDeclaration;//添加文档类型
            XElement rootElement = new XElement("school");//创建根节点
            xDoc.Add(rootElement);//将school节点添加进文档中
            XElement xClass = new XElement("class");//创建一个class元素
            xClass.SetAttributeValue("id", "c01");//为class标签添加属性和值。
            rootElement.Add(xClass);
            XElement student = new XElement("student");
            student.SetAttributeValue("id", "s001");//为student节点设置属性
            student.SetElementValue("Name", "curry");//在student节点中,添加叶子节点Name,值为curry
            student.SetElementValue("age", 17);//在student节点中,添加叶子节点age,值为17
            student.SetElementValue("sex", "male");//在student节点中,添加叶子节点sex,值为male
            xClass.Add(student);//将student节点添加到class节点中去。
            xDoc.Save("xuexiao.xml");//如果这个文件不存在,那么就会创建一个并写入内容。如果这个文件存在,那么就会覆盖掉内容。
3.0以后的版本

 

C# 操作XML

标签:分享   color   ati   innertext   说明   图片   写入   code   root   

原文地址:https://www.cnblogs.com/vichin/p/8215612.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!