XML是什么就不用说了文本标记语言。html
主要纪录如何对XML文件进行增删改查。node
Xml的操做类都存在System.xml命名空间下面。spa
应用型的直接上代码code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace XMLTest { class Program { static void Main(string[] args) { //1.建立XML文档对象 XmlDocument doc = new XmlDocument(); //建立头 XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); //添加节点 doc.AppendChild(xmlDeclaration); XmlElement xmlElement = doc.CreateElement("Persons"); //给节点添加属性 xmlElement.SetAttribute("Name", "一小时小超人"); doc.AppendChild(xmlElement); XmlElement xmlElement1 = doc.CreateElement("Person"); //给节点添加文字 xmlElement1.InnerXml = "小超人"; xmlElement.AppendChild(xmlElement1); doc.Save("Test.xml"); } } }
<?xml version="1.0" encoding="UTF-8"?> <Persons Name="一小时小超人"> <Person>小超人</Person> </Persons>
这个地方主要讲一下 XmlElement.InnerXml和XmlElement.InnerText的区别。代码演示xml
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace XMLTest { class Program { static void Main(string[] args) { //1.建立XML文档对象 XmlDocument doc = new XmlDocument(); //建立头 XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); //添加节点 doc.AppendChild(xmlDeclaration); XmlElement xmlElement = doc.CreateElement("Persons"); //给节点添加属性 xmlElement.SetAttribute("Name", "一小时小超人"); doc.AppendChild(xmlElement); XmlElement xmlElement1 = doc.CreateElement("Person"); //给节点添加文字 xmlElement1.InnerXml = "<演示>小超人</演示>"; xmlElement.AppendChild(xmlElement1); XmlElement xmlElement2 = doc.CreateElement("Person"); //给节点添加文字 xmlElement2.InnerText = "<演示>小超人</演示>";
//给节点添加属性
xmlElement2.SetAttribute("name", "一小时小超人");htm
xmlElement.AppendChild(xmlElement2); doc.Save("Test.xml"); } } }
<?xml version="1.0" encoding="UTF-8"?> <Persons Name="一小时小超人"> <Person> <演示>小超人</演示> </Person> <Person name="一小时小超人"><演示>小超人</演示></Person> </Persons>
很明显的看出来若是字符串是个标签,Interxml会当成标签给你添加,innterText会转义。对象
下面演示一下读取操做blog
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace XMLTest { class Program { static void Main(string[] args) { //1.建立XML文档对象 XmlDocument doc = new XmlDocument(); if (File.Exists("Test.xml")) { //经过文件名加载Xml,也能够经过流之类的,其余重载方法,看文档。 doc.Load("Test.xml"); //获取根节点 XmlElement xmlElement = doc.DocumentElement; //获取根节点下面的子节点集合 XmlNodeList nodeList = xmlElement.ChildNodes; //循环取每个子节点 foreach (XmlNode item in nodeList) { Console.WriteLine(item.Name); //获取节点属性 //string attributesValue=item.Attributes["属性名称"].Value; } Console.ReadKey(); } } } }
上面代码把经常使用的操做列出来了,其余的不少操做。就不一一列举了。。。。。。。。。。。。。文档