這篇文章給大家分享的是有關如何使用xml的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
1、 認識xml
可擴展標記語言,一種用于標記電子文檔使其具有結果性的標記語言,它可以用來標記數據、定義數據類型,是一種允許用戶對自己的標記語言進行定義的源語言。
2、 和超文本標記語言區別
2.1 html不一定需要成對出現,xml則一定需要成對出現。
2.2 html 不區分大小寫,但是xml區分。
3、對xml文檔增刪改查
//聲明一個XmlDocument空對象 protected XmlDocument XmlDoc = new XmlDocument(); /// <summary> /// 構造函數,導入xml文件 /// </summary> /// <param name="path"></param> public XmlHelper(string path) { try { XmlDoc.Load(path); } catch (Exception ex) { throw ex; } } /// <summary> /// 保存文件 /// </summary> /// <param name="path"></param> public void SaveXml(string path) { try { XmlDoc.Save(path); } catch (System.Exception ex) { throw ex; } }
/// <summary> /// 獲取節點的子節點的內容 /// </summary> /// <param name="path"></param> /// <param name="rootNode"></param> /// <param name="attributeName"></param> /// <returns></returns> public string GetNodeChildAttribute(string path, string rootNode, string attributeName) { XmlNode xn = XmlDoc.SelectSingleNode(rootNode); StringBuilder sb = new StringBuilder(); XmlNodeList xnl = xn.ChildNodes; foreach (XmlNode xnf in xnl) { XmlElement xe = (XmlElement)xnf; XmlNodeList xnf1 = xe.ChildNodes; foreach (XmlNode xn2 in xnf1) { if (xn2.Name == attributeName) { sb.Append(xn2.InnerText);//顯示子節點點文本 } } } return sb.ToString(); }
/// <summary> /// 獲取節點的屬性值 /// </summary> /// <param name="path">xml路徑</param> /// <param name="rootNode">根節點名稱</param> /// <param name="attributeName">屬性名稱</param> /// <returns></returns> public string GetNodeAttribute(string path, string rootNode, string attributeName) { try { XmlNode xn = XmlDoc.SelectSingleNode(rootNode); XmlNodeList xnl = xn.ChildNodes; StringBuilder sb = new StringBuilder(); foreach (XmlNode xnf in xnl) { XmlElement xe = (XmlElement)xnf; sb.Append(xe.GetAttribute(attributeName)); } return sb.ToString(); } catch (Exception) { throw; } }
/// <summary> /// 刪除節點/節點屬性 /// </summary> /// <param name="path">xml文件地址</param> /// <param name="rootNode">根節點名稱</param> /// <param name="delNode">要刪除的節點</param> /// <param name="attributeName">節點屬性</param> /// <param name="attributeValue">屬性值</param> public void DeleteNode(string path, string rootNode, string attributeName, string attributeValue) { try { XmlNodeList xnl = XmlDoc.SelectSingleNode(rootNode).ChildNodes; foreach (XmlNode xn in xnl) { XmlElement xe = (XmlElement)xn; if (xe.GetAttribute(attributeName) == attributeValue) { //xe.RemoveAttribute(attributeName);//刪除屬性 xe.RemoveAll();//刪除該節點的全部內容 } } SaveXml(path); } catch (Exception) { throw; } }
/// <summary> /// 修改節點的子節點內容 /// </summary> /// <param name="path">xml文件路徑</param> /// <param name="rootNode">根節點名稱</param> /// <param name="attributeName">節點的子節點名稱</param> /// <param name="attributeOldValue">節點的子節點原始內容</param> /// <param name="attributeNewValue">節點的子節點新內容</param> public void UpdateChildNodeAttribute(string path, string rootNode, string attributeName,string attributeOldValue, string attributeNewValue) { try { XmlNodeList nodeList = XmlDoc.SelectSingleNode(rootNode).ChildNodes;//獲取根節點的所有子節點 foreach (XmlNode xn in nodeList)//遍歷所有子節點 { XmlElement xe = (XmlElement)xn;//將子節點類型轉換為XmlElement類型 if (string.IsNullOrEmpty(attributeName) || string.IsNullOrEmpty(attributeOldValue)) { return; } else { XmlNodeList nls = xe.ChildNodes; if (nls != null && nls.Count > 0) { foreach (XmlNode xn1 in nls)//遍歷 { XmlElement xe2 = (XmlElement)xn1;//轉換類型 if (xe2.InnerText == attributeOldValue)//如果找到 { xe2.InnerText = attributeNewValue;//則修改 break;//找到退出來就可以了 } } } } } SaveXml(path); } catch (Exception) { throw; } }
/// <summary> /// 修改節點屬性值操作 /// </summary> /// <param name="path">xml文件路徑</param> /// <param name="rootNode">根節點名稱,如:bookstore</param> /// <param name="attributeName">節點屬性名</param> /// <param name="attributeOldValue">節點屬性原來值</param> /// <param name="attributeNewValue">節點屬性修改后的值</param> public void UpdateNodeAttribute(string path, string rootNode, string attributeName, string attributeOldValue, string attributeNewValue) { try { XmlNodeList nodeList = XmlDoc.SelectSingleNode(rootNode).ChildNodes;//獲取根節點的所有子節點 foreach (XmlNode xn in nodeList)//遍歷所有子節點 { XmlElement xe = (XmlElement)xn;//將子節點類型專程xmlelement類型 if (string.IsNullOrEmpty(attributeName) || string.IsNullOrEmpty(attributeOldValue)) { return; } else { if (xe.GetAttribute(attributeName) == attributeOldValue) { xe.SetAttribute(attributeName, attributeNewValue); } } } SaveXml(path); } catch (Exception) { throw; } }
/// <summary> /// 插入節點操作 /// </summary> /// <param name="path">xml文件路徑</param> /// <param name="rootNode">根節點名稱,如:bookstore</param> /// <param name="node">節點名稱,如:book</param> /// <param name="nodeAttributes">節點的屬性-屬性值集合</param> /// <param name="childAttributes">節點子節點名稱-內容</param> public void InsertNode(string path, string rootNode, string node, Dictionary <string, string> nodeAttributes, Dictionary<string, string> childAttributes) { try { XmlNode root = XmlDoc.SelectSingleNode(rootNode);//找到根節點bookstore XmlElement xe1 = XmlDoc.CreateElement(node);//創建子節點book if (nodeAttributes != null && nodeAttributes.Count > 0) { foreach (var n in nodeAttributes) { xe1.SetAttribute(n.Key, n.Value); } } if (childAttributes != null && childAttributes.Count > 0) { XmlElement xesub1; foreach (var n in childAttributes) { xesub1 = XmlDoc.CreateElement(n.Key); xesub1.InnerText = n.Value; xe1.AppendChild(xesub1);//添加到<book>節點中 } } root.AppendChild(xe1); SaveXml(path); } catch (Exception) { throw; } }
調用:
string path = Server.MapPath("Books.xml"); XmlHelper xHelper = new XmlHelper(path); /*插入*/ //Dictionary<string, string> dc1 = new Dictionary<string, string>(); //dc1.Add("genre", "李贊紅"); //dc1.Add("ISBN", "2-3631-4"); //Dictionary<strin插入g, string> dc2 = new Dictionary<string, string>(); //dc2.Add("title", "CS從入門到精通"); //dc2.Add("author", "候捷"); //dc2.Add("price", "58.3"); //xHelper.InsertNode(path, "bookstore", "book", dc1, dc2); /*修改*/ //xHelper.UpdateNodeAttribute(path, "bookstore", "genre", "李贊紅", "李"); //xHelper.UpdateChildNodeAttribute(path, "bookstore", "title", "CS從入門到精通", "cs"); /*刪除節點*/ //xHelper.DeleteNode(path, "bookstore", "genre", "李"); //Response.Write(xHelper.GetNodeAttribute(path, "bookstore", "genre")); //Response.Write(xHelper.GetNodeChildAttribute(path, "bookstore", "price"));
4、通過xml數據綁定
xml轉DataTable
public DataTable XmlToData(string path, string rootNode, params string[] columns) { DataTable dt = new DataTable(); XmlNodeList xn = XmlDoc.SelectSingleNode(rootNode).ChildNodes; try { if (columns.Length > 0) { DataColumn dc; for (int i = 0; i < columns.Length; i++) { dc = new DataColumn(columns[i]); dt.Columns.Add(dc); } foreach (XmlNode xnf in xn) { XmlElement xe = (XmlElement)xnf; XmlNodeList xnf1 = xe.ChildNodes; int i = 0; DataRow dr = dt.NewRow(); foreach (XmlNode xn2 in xnf1) { dr[i] = xn2.InnerText; i++; } dt.Rows.Add(dr); } } } catch (Exception) { throw; } return dt; }
調用:
//string[] arr = { "title", "author", "price" }; //GridView1.DataSource = xHelper.XmlToData(path, "bookstore", arr); //GridView1.DataBind();
DataTable轉xml
/*datatable轉xml*/ public string DataTableToXml(DataTable dt) { if (dt != null) { MemoryStream ms = null; XmlTextWriter XmlWt = null; try { ms = new MemoryStream(); //根據ms實例化XmlWt XmlWt = new XmlTextWriter(ms, Encoding.Unicode); //獲取ds中的數據 dt.WriteXml(XmlWt); int count = (int)ms.Length; byte[] temp = new byte[count]; ms.Seek(0, SeekOrigin.Begin); ms.Read(temp, 0, count); //返回Unicode編碼的文本 UnicodeEncoding ucode = new UnicodeEncoding(); string returnValue = ucode.GetString(temp).Trim(); return returnValue; } catch (System.Exception ex) { throw ex; } finally { //釋放資源 if (XmlWt != null) { XmlWt.Close(); ms.Close(); ms.Dispose(); } } } else { return ""; } }
調用:
//bool s = xHelper.CDataToXmlFile(xHelper.XmlToData(path, "bookstore", arr), "Bookss.xml","book");
5、xml序列化反序列化
[Serializable] public class Person { public string Name { get; set; } public int Age { get; set; } }
public class CXmlSerializer<T> where T : new() { private static XmlSerializer _Serializer = new XmlSerializer(typeof(T)); public static string Serialize(T t) { string s = ""; using (MemoryStream ms = new MemoryStream()) { _Serializer.Serialize(ms, t); s = System.Text.UTF8Encoding.UTF8.GetString(ms.ToArray()); } return s; } public static T Deserialize(string s) { T t; using (MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(s))) { t = (T)_Serializer.Deserialize(ms); } return t; } }
調用:
List<Person> list = new List<Person> { new Person { Name = "Xuj", Age = 20 }, new Person { Name = "duj", Age = 20 }, new Person { Name = "fuj", Age = 20 } }; string s = CXmlSerializer<List<Person>>.Serialize(list);
感謝各位的閱讀!關于“如何使用xml”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。