XML文件是一种以简单文本格式存储数据的方式。下面介绍XML文件的几中基本操作。
1、新建XML文件
- /// <summary>
- /// 1.新建XML文件
- /// </summary>
- public static void CreateXML()
- {
- XmlDocument doc = new XmlDocument();
- //xml declaration (xml声明)
- XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0","utf-8",null);
- XmlNode rootNode = doc.CreateNode(XmlNodeType.Element,"v","Games","www-microsoft-game");
- doc.AppendChild(rootNode);
- XmlNode node1 = doc.CreateNode(XmlNodeType.Element,"Game","www-microsoft-game");
- rootNode.AppendChild(node1);
- node1.Attributes.Append(doc.CreateAttribute("name")).InnerText = "文明3";
-
- node1.AppendChild(doc.CreateNode(XmlNodeType.Element,"Price",null)).InnerText = "100";
- XmlNode node2 = doc.CreateNode(XmlNodeType.Element,"www-microsoft-game");
- rootNode.AppendChild(node2);
- node2.Attributes.Append(doc.CreateAttribute("name")).InnerText = "帝国时代";
-
- node2.AppendChild(doc.CreateNode(XmlNodeType.Element,null)).InnerText = "300";
- doc.InsertBefore(declaration,doc.DocumentElement);
- doc.Save("game.xml");
- }
2、插入节点
- /// <summary>
- /// 2.插入节点
- /// </summary>
- public static void InsertNode()
- {
- //1.加载XML document
- XmlDocument doc = new XmlDocument();
- doc.Load(@"game.xml");
- //Get the root element
- XmlNode rootNode = doc.DocumentElement;
-
- //create the new game
- XmlNode newNode = doc.CreateNode(XmlNodeType.Element,"www-microsoft-game");
- rootNode.AppendChild(newNode);
- newNode.Attributes.Append(doc.CreateAttribute("name")).InnerText = "帝国时代X";
-
- newNode.AppendChild(doc.CreateNode(XmlNodeType.Element,null)).InnerText = "300";
-
- doc.Save("newgame.xml");
-
- }
3、删除节点
- /// <summary>
- /// 3.删除节点
- /// </summary>
- public static void DeleteNode()
- {
- XmlDocument doc = new XmlDocument();
-
- doc.Load("newGame.xml");
-
- XmlNode root = doc.DocumentElement;
- if (root.HasChildNodes)
- {
- XmlNode game = root.LastChild;
- root.RemoveChild(game);
- doc.Save("newGame2.xml");
- }
-
- }
4、更新节点
- /// <summary>
- /// 4.更新节点
- /// </summary>
- public static void UpdateNode()
- {
- XmlDocument doc = new XmlDocument();
- doc.Load("game.xml");
- XmlNode root = doc.DocumentElement;
- XmlNamespaceManager nsmgr =
- new XmlNamespaceManager(
- new XmlDocument().NaMetable);
- //建立Xml命名空间管理器对象
- nsmgr.AddNamespace("v","www-microsoft-game");
- //XmlNode updateNode = root.SelectSingleNode()
- XmlNode updateNode = doc.SelectSingleNode("v:Games/v:Game[@name='文明3']/Price",nsmgr);
-
- updateNode.InnerText =" 330";
- doc.Save("gamex.xml");
-
- }
参考资料:C# 操作XML之读取Xml浅析,http://developer.51cto.com/art/200908/144648.htm
C# 操作XML之建立Xml对象浅析 ,http://developer.51cto.com/art/200908/144652.htm
C#入门经典(第五版)中文版,第22章 XML p623-p645