在.net的項目開發中,經常會對XML文件進行操作,由於XML文件可以實現跨平台傳輸,較多的應用在數據傳輸中,特總結以下幾種常用的XML操作方法:
1.創建XML文檔:
/// <summary> /// 創建XML文檔 /// </summary> /// <param name="name">根節點名稱</param> /// <param name="type">根節點的一個屬性值</param> /// <returns>XmlDocument對象</returns> public static XmlDocument CreateXmlDocument(string name, string type) { XmlDocument doc; try { doc = new XmlDocument(); doc.LoadXml("<" + name + "/>"); var rootEle = doc.DocumentElement; rootEle?.SetAttribute("type", type); } catch (Exception er) { throw new Exception(er.ToString()); } return doc; }
2.讀取XML文檔中的數據:
/// <summary> /// 讀取數據 /// </summary> /// <param name="path">路徑</param> /// <param name="node">節點</param> /// <param name="attribute">屬性名,非空時返回該屬性值,否則返回串聯值</param> /// <returns>string</returns> public static string Read(string path, string node, string attribute) { var value = ""; try { var doc = new XmlDocument(); doc.Load(path); var xn = doc.SelectSingleNode(node); if (xn != null && xn.Attributes != null) value = (attribute.Equals("") ? xn.InnerText : xn.Attributes[attribute].Value); } catch (Exception er) { throw new Exception(er.ToString()); } return value; }
3.對XML文檔插入數據:
/// <summary> /// 插入數據 /// </summary> /// <param name="path">路徑</param> /// <param name="node">節點</param> /// <param name="element">元素名,非空時插入新元素,否則在該元素中插入屬性</param> /// <param name="attribute">屬性名,非空時插入該元素屬性值,否則插入元素值</param> /// <param name="value">值</param> /// <returns></returns> public static void Insert(string path, string node, string element, string attribute, string value) { try { var doc = new XmlDocument(); doc.Load(path); var xn = doc.SelectSingleNode(node); if (element.Equals("")) { if (!attribute.Equals("")) { var xe = (XmlElement)xn; xe?.SetAttribute(attribute, value); //xe?.SetAttribute(attribute, value); } } else { var xe = doc.CreateElement(element); if (attribute.Equals("")) xe.InnerText = value; else xe.SetAttribute(attribute, value); xn?.AppendChild(xe); } doc.Save(path); } catch (Exception er) { throw new Exception(er.ToString()); } }
4.修改XML文檔中的數據:
/// <summary> /// 修改數據 /// </summary> /// <param name="path">路徑</param> /// <param name="node">節點</param> /// <param name="attribute">屬性名,非空時修改該節點屬性值,否則修改節點值</param> /// <param name="value">值</param> /// <returns></returns> public static void Update(string path, string node, string attribute, string value) { try { var doc = new XmlDocument(); doc.Load(path); var xn = doc.SelectSingleNode(node); var xe = (XmlElement)xn; if (attribute.Equals("")) { if (xe != null) xe.InnerText = value; } else { xe?.SetAttribute(attribute, value); } doc.Save(path); } catch (Exception er) { throw new Exception(er.ToString()); } }
5.刪除XML文檔中數據:
/// <summary> /// 刪除數據 /// </summary> /// <param name="path">路徑</param> /// <param name="node">節點</param> /// <param name="attribute">屬性名,非空時刪除該節點屬性值,否則刪除節點值</param> /// <returns></returns> public static void Delete(string path, string node, string attribute) { try { var doc = new XmlDocument(); doc.Load(path); var xn = doc.SelectSingleNode(node); var xe = (XmlElement)xn; if (attribute.Equals("")) { xn?.ParentNode?.RemoveChild(xn); } else { xe?.RemoveAttribute(attribute); } doc.Save(path); } catch (Exception er) { throw new Exception(er.ToString()); } }
6.讀取XML文檔中指定節點數據:
/// <summary> /// 獲得xml文件中指定節點的節點數據 /// </summary> /// <param name="path"></param> /// <param name="nodeName"></param> /// <returns></returns> public static string GetNodeInfoByNodeName(string path, string nodeName) { var xmlString = string.Empty; try { var xml = new XmlDocument(); xml.Load(path); var root = xml.DocumentElement; if (root == null) return xmlString; var node = root.SelectSingleNode("//" + nodeName); if (node != null) { xmlString = node.InnerText; } } catch (Exception er) { throw new Exception(er.ToString()); } return xmlString; }
7.獲取XML指定節點的屬性:
/// <summary> /// 功能:讀取指定節點的指定屬性值 /// </summary> /// <param name="path"></param> /// <param name="strNode">節點名稱</param> /// <param name="strAttribute">此節點的屬性</param> /// <returns></returns> public string GetXmlNodeAttributeValue(string path, string strNode, string strAttribute) { var strReturn = ""; try { var xml = new XmlDocument(); xml.Load(path); //根據指定路徑獲取節點 var xmlNode = xml.SelectSingleNode(strNode); if (xmlNode != null) { //獲取節點的屬性,並循環取出需要的屬性值 var xmlAttr = xmlNode.Attributes; if (xmlAttr == null) return strReturn; for (var i = 0; i < xmlAttr.Count; i++) { if (xmlAttr.Item(i).Name != strAttribute) continue; strReturn = xmlAttr.Item(i).Value; break; } } } catch (XmlException xmle) { throw new Exception(xmle.Message); } return strReturn; }
8.設置XML文檔中指定節點的屬性:
/// <summary> /// 功能:設置節點的屬性值 /// </summary> /// <param name="path"></param> /// <param name="xmlNodePath">節點名稱</param> /// <param name="xmlNodeAttribute">屬性名稱</param> /// <param name="xmlNodeAttributeValue">屬性值</param> public void SetXmlNodeAttributeValue(string path, string xmlNodePath, string xmlNodeAttribute, string xmlNodeAttributeValue) { try { var xml = new XmlDocument(); xml.Load(path); //可以批量為符合條件的節點的屬性付值 var xmlNode = xml.SelectNodes(xmlNodePath); if (xmlNode == null) return; foreach (var xmlAttr in from XmlNode xn in xmlNode select xn.Attributes) { if (xmlAttr == null) return; for (var i = 0; i < xmlAttr.Count; i++) { if (xmlAttr.Item(i).Name != xmlNodeAttribute) continue; xmlAttr.Item(i).Value = xmlNodeAttributeValue; break; } } } catch (XmlException xmle) { throw new Exception(xmle.Message); } }
9.讀取XML文檔指定節點的值:
/// <summary> /// 讀取XML資源中的指定節點內容 /// </summary> /// <param name="source">XML資源</param> /// <param name="xmlType">XML資源類型:文件,字符串</param> /// <param name="nodeName">節點名稱</param> /// <returns>節點內容</returns> public static object GetNodeValue(string source, XmlType xmlType, string nodeName) { var xd = new XmlDocument(); if (xmlType == XmlType.File) { xd.Load(source); } else { xd.LoadXml(source); } var xe = xd.DocumentElement; XmlNode xn = null; if (xe != null) { xn= xe.SelectSingleNode("//" + nodeName); } return xn.InnerText; }
10.更新XML文檔指定節點的內容:
/// <summary> /// 更新XML文件中的指定節點內容 /// </summary> /// <param name="filePath">文件路徑</param> /// <param name="nodeName">節點名稱</param> /// <param name="nodeValue">更新內容</param> /// <returns>更新是否成功</returns> public static bool UpdateNode(string filePath, string nodeName, string nodeValue) { try { bool flag; var xd = new XmlDocument(); xd.Load(filePath); var xe = xd.DocumentElement; if (xe == null) return false; var xn = xe.SelectSingleNode("//" + nodeName); if (xn != null) { xn.InnerText = nodeValue; flag = true; } else { flag = false; } return flag; } catch (Exception ex) { throw new Exception(ex.Message); } }
11.將對象轉化為XML文件,並存入指定目錄:
/// <summary> /// 將對象轉化為xml,並寫入指定路徑的xml文件中 /// </summary> /// <typeparam name="T">C#對象名</typeparam> /// <param name="item">對象實例</param> /// <param name="path">路徑</param> /// <param name="jjdbh">標號</param> /// <param name="ends">結束符號(整個xml的路徑類似如下:C:\xmltest\201111send.xml,其中path=C:\xmltest,jjdbh=201111,ends=send)</param> /// <returns></returns> public static string WriteXml<T>(T item, string path, string jjdbh, string ends) { if (string.IsNullOrEmpty(ends)) { //默認為發送 ends = "send"; } //控制寫入文件的次數 var i = 0; //獲取當前對象的類型,也可以使用反射typeof(對象名) var serializer = new XmlSerializer(item.GetType()); //xml的路徑組合 object[] obj = { path, "\\", jjdbh, ends, ".xml" }; var xmlPath = string.Concat(obj); while (true) { try { //用filestream方式創建文件不會出現“文件正在占用中,用File.create”則不行 var fs = System.IO.File.Create(xmlPath); fs.Close(); TextWriter writer = new StreamWriter(xmlPath, false, Encoding.UTF8); var xml = new XmlSerializerNamespaces(); xml.Add(string.Empty, string.Empty); serializer.Serialize(writer, item, xml); writer.Flush(); writer.Close(); break; } catch (Exception) { if (i < 5) { i++; continue; } break; } } return SerializeToXmlStr<T>(item, true); }
12.向一個已經存在的父節點中插入一個子節點:
/// <summary> /// 向一個已經存在的父節點中插入一個子節點 /// </summary> /// <param name="path"></param> /// <param name="parentNodePath">父節點</param> /// <param name="childnodename">子節點名稱</param> public void AddChildNode(string path, string parentNodePath, string childnodename) { try { var xml = new XmlDocument(); xml.Load(path); var parentXmlNode = xml.SelectSingleNode(parentNodePath); XmlNode childXmlNode = xml.CreateElement(childnodename); if ((parentXmlNode) != null) { //如果此節點存在 parentXmlNode.AppendChild(childXmlNode); } else { //如果不存在就放父節點添加 GetXmlRoot(path).AppendChild(childXmlNode); } } catch (XmlException xmle) { throw new Exception(xmle.Message); } }
以上的方法總結采用.net4.5版本和c#6.0語法