C#操作Xml的基本方法

发布时间:2020-06-27 20:52:00 作者:彭泽0902
来源:网络 阅读:875

   在.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>
        /// 将对象转化为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);
        }

  以上的方法总结采用.net4.5版本和c#6.0语法。

推荐阅读:
  1. 操作mysql数据表的基本方法
  2. c# 操作 xml

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

net xml

上一篇:计算机语言&Python解释器

下一篇:Windows temp 用户等

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》