溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C#操作Xml的基本方法

發(fā)布時間:2020-06-27 20:52:00 來源:網(wǎng)絡(luò) 閱讀:875 作者:彭澤0902 欄目:編程語言

   在.net的項目開發(fā)中,經(jīng)常會對XML文件進行操作,由于XML文件可以實現(xiàn)跨平臺傳輸,較多的應(yīng)用在數(shù)據(jù)傳輸中,特總結(jié)以下幾種常用的XML操作方法:

1.創(chuàng)建XML文檔:

        /// <summary>
        /// 創(chuàng)建XML文檔
        /// </summary>
        /// <param name="name">根節(jié)點名稱</param>
        /// <param name="type">根節(jié)點的一個屬性值</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文檔中的數(shù)據(jù):

        /// <summary>
        /// 讀取數(shù)據(jù)
        /// </summary>
        /// <param name="path">路徑</param>
        /// <param name="node">節(jié)點</param>
        /// <param name="attribute">屬性名,非空時返回該屬性值,否則返回串聯(lián)值</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文檔插入數(shù)據(jù):

        /// <summary>
        /// 插入數(shù)據(jù)
        /// </summary>
        /// <param name="path">路徑</param>
        /// <param name="node">節(jié)點</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文檔中的數(shù)據(jù):

        /// <summary>
        /// 修改數(shù)據(jù)
        /// </summary>
        /// <param name="path">路徑</param>
        /// <param name="node">節(jié)點</param>
        /// <param name="attribute">屬性名,非空時修改該節(jié)點屬性值,否則修改節(jié)點值</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文檔中數(shù)據(jù):

        /// <summary>
        /// 刪除數(shù)據(jù)
        /// </summary>
        /// <param name="path">路徑</param>
        /// <param name="node">節(jié)點</param>
        /// <param name="attribute">屬性名,非空時刪除該節(jié)點屬性值,否則刪除節(jié)點值</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文檔中指定節(jié)點數(shù)據(jù):

        /// <summary>
        /// 獲得xml文件中指定節(jié)點的節(jié)點數(shù)據(jù)
        /// </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("http://" + nodeName);
                if (node != null)
                {
                    xmlString = node.InnerText;
                }
            }
            catch (Exception er)
            {
                throw new Exception(er.ToString());
            }
            return xmlString;
        }

7.獲取XML指定節(jié)點的屬性:

        /// <summary>  
        /// 功能:讀取指定節(jié)點的指定屬性值     
        /// </summary>
        /// <param name="path"></param>
        /// <param name="strNode">節(jié)點名稱</param>  
        /// <param name="strAttribute">此節(jié)點的屬性</param>  
        /// <returns></returns>  
        public string GetXmlNodeAttributeValue(string path, string strNode, string strAttribute)
        {
            var strReturn = "";
            try
            {
                var xml = new XmlDocument();
                xml.Load(path);
                //根據(jù)指定路徑獲取節(jié)點  
                var xmlNode = xml.SelectSingleNode(strNode);
                if (xmlNode != null)
                {
                    //獲取節(jié)點的屬性,并循環(huán)取出需要的屬性值  
                    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.將對象轉(zhuǎn)化為XML文件,并存入指定目錄:

        /// <summary>
        /// 將對象轉(zhuǎn)化為xml,并寫入指定路徑的xml文件中
        /// </summary>
        /// <typeparam name="T">C#對象名</typeparam>
        /// <param name="item">對象實例</param>
        /// <param name="path">路徑</param>
        /// <param name="jjdbh">標號</param>
        /// <param name="ends">結(jié)束符號(整個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))
            {
                //默認為發(fā)送
                ends = "send";
            }
            //控制寫入文件的次數(shù)
            var i = 0;
            //獲取當(dāng)前對象的類型,也可以使用反射typeof(對象名)
            var serializer = new XmlSerializer(item.GetType());
            //xml的路徑組合
            object[] obj = { path, "\\", jjdbh, ends, ".xml" };
            var xmlPath = string.Concat(obj);
            while (true)
            {
                try
                {
                    //用filestream方式創(chuàng)建文件不會出現(xiàn)“文件正在占用中,用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);
        }

  以上的方法總結(jié)采用.net4.5版本和c#6.0語法。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI