C#操作XML通用辦法匯總。本站提示廣大學習愛好者:(C#操作XML通用辦法匯總)文章只能為提供參考,不一定能成為您想要的結果。以下是C#操作XML通用辦法匯總正文
在.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語法,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。