C#中對xml數據的讀取和寫入:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using System.Xml; using Newtonsoft.Json; namespace cashUI.test { class XmlTest { private static string localPath = System.Environment.CurrentDirectory + @"\test\"; /* * 寫入xml */ public void writeXml() { string path = localPath + "/test.xml"; XmlDocument docment = new XmlDocument(); XmlNode node = docment.AppendChild(docment.CreateXmlDeclaration("1.0", "UTF-8", null)); XmlElement users = docment.CreateElement("Users");//一級節點 XmlElement user = docment.CreateElement("User");//二級節點 //創建三級節點 XmlElement userName = docment.CreateElement("userName"); userName.InnerText = "root111"; XmlElement passWord = docment.CreateElement("passWord"); passWord.InnerText = "123456"; //三級節點加入到二級節點中 user.AppendChild(userName); user.AppendChild(passWord); users.AppendChild(user); docment.AppendChild(users); docment.Save(path); } /* * 讀取修改xml */ public void readXml() { string path = localPath + "/test.xml"; XmlDocument docment = new XmlDocument(); docment.Load(path); XmlNode rootNode = docment.SelectSingleNode("Users"); for (int i = 0; i < rootNode.ChildNodes.Count; i++) { if (rootNode.ChildNodes[i].ChildNodes[0].InnerText == "root111") { rootNode.ChildNodes[i].ChildNodes[0].InnerText = "root222"; rootNode.ChildNodes[i].ChildNodes[1].InnerText = "654321"; } } docment.Save(path); } /* * xml轉成json * 把xml讀取轉成對象,把對象轉json */ public void xml2json() { //1.讀取xml的數據 string path = localPath + "/test.xml"; XmlDocument docment = new XmlDocument(); docment.Load(path); //string jsonText = JsonConvert.SerializeXmlNode(docment); //2.把讀取出來的xml數據循環放進key->value字典類型中 List<Dictionary<string, string>> list = new List<Dictionary<string, string>>(); XmlNode rootNode = docment.SelectSingleNode("Users"); for (int i = 0; i < rootNode.ChildNodes.Count; i++) { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add(rootNode.ChildNodes[i].ChildNodes[0].Name, rootNode.ChildNodes[i].ChildNodes[0].InnerText); dic.Add(rootNode.ChildNodes[i].ChildNodes[1].Name, rootNode.ChildNodes[i].ChildNodes[1].InnerText); list.Add(dic); } Dictionary<string, List<Dictionary<string, string>>> dict = new Dictionary<string, List<Dictionary<string, string>>>(); dict.Add("data", list); //3.把對象型的數據轉json string jsonText = JsonConvert.SerializeObject(dict); Console.WriteLine(jsonText); //return jsonText; } } }