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(); } } } }
上面代碼把經常使用的操做列出來了,其餘的不少操做。就不一一列舉了。。。。。。。。。。。。。文檔