通过XmlDocument编辑Xml
发布时间:2020-12-15 23:42:41 所属栏目:百科 来源:网络整理
导读:我们常常需要编辑和读取XML文件,而方式有很多,这里主要列出使用XmlDocument来进行操作。 其中主要涉及 XmlDocument类、XmlDocument类、XmlAttribute类。 1. 每一个子节点都需要 XmlDocument的 CreateElement() 方法来进行创建。 2. 添加节点到父节点,由
我们常常需要编辑和读取XML文件,而方式有很多,这里主要列出使用XmlDocument来进行操作。
其中主要涉及XmlDocument类、XmlDocument类、XmlAttribute类。
1. 每一个子节点都需要XmlDocument的CreateElement()方法来进行创建。
2. 添加节点到父节点,由父节点的AppendChild()方法来添加。
3. 每一个节点的属性都需要XmlDocument的CreateAttribute()方法来进行创建。
4. 设置节点的内容,用InnerText()方法来进行添加。
示例代码:(代码来自
http://weibo.com/yukaizhao,)
using System; using System.Collections.Generic; using System.Text; using System.Xml; namespace WriteXml { class Program { static void Main(string[] args) { XmlDocument xmlDoc = new XmlDocument(); //创建Xml声明部分,即<?xml version="1.0" encoding="utf-8" ?> xmlDoc.CreateXmlDeclaration("1.0","utf-8","yes"); //创建根节点 XmlNode rootNode = xmlDoc.CreateElement("students"); //创建student子节点 XmlNode studentNode = xmlDoc.CreateElement("student"); //创建一个属性 XmlAttribute nameAttribute = xmlDoc.CreateAttribute("name"); nameAttribute .Value = "张同学"; //xml节点附件属性 studentNode.Attributes.Append(nameAttribute); //创建courses子节点 XmlNode coursesNode = xmlDoc.CreateElement("courses"); XmlNode courseNode1 = xmlDoc.CreateElement("course"); XmlAttribute courseNameAttr = xmlDoc.CreateAttribute("name"); courseNameAttr.Value = "语文"; courseNode1.Attributes.Append(courseNameAttr); XmlNode teacherCommentNode = xmlDoc.CreateElement("teacherComment"); //创建Cdata块 XmlCDataSection cdata = xmlDoc.CreateCDataSection("<font color="red">这是批注</font>"); teacherCommentNode.AppendChild(cdata); courseNode1.AppendChild(teacherCommentNode); coursesNode.AppendChild(courseNode1); //附加子节点 studentNode.AppendChild(coursesNode); rootNode.AppendChild(studentNode); //附加根节点 xmlDoc.AppendChild(rootNode); //保存Xml文档 xmlDoc.Save(@"d:test.xml"); Console.WriteLine("已保存Xml文档"); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |