详细介绍xml的使用方法总结

1、 认识xml

可扩展标记语言,一种用于标记电子文档使其具有结果性的标记语言,它可以用来标记数据、定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言。

2、 和超文本标记语言区别

2.1 html不一定需要成对出现,xml则一定需要成对出现。

2.2 html 不区分大小写,但是xml区分。

3、对xml文档增删改查

//声明一个XmlDocument空对象       protected XmlDocument XmlDoc = new XmlDocument();       ///        /// 构造函数,导入xml文件       ///        ///        public XmlHelper(string path)       {           try           {               XmlDoc.Load(path);           }           catch (Exception ex)           {               throw ex;           }       }       ///        /// 保存文件       ///        ///        public void SaveXml(string path)       {           try           {               XmlDoc.Save(path);           }           catch (System.Exception ex)           {               throw ex;           }       }

登录后复制

///        /// 获取节点的子节点的内容       ///        ///        ///        ///        ///        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();       }

登录后复制

///         /// 获取节点的属性值        ///         /// xml路径        /// 根节点名称        /// 属性名称        ///         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;            }        }

登录后复制

///        /// 删除节点/节点属性       ///        /// xml文件地址       /// 根节点名称       /// 要删除的节点       /// 节点属性       /// 属性值       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;           }       }

登录后复制

///        /// 修改节点的子节点内容       ///        /// xml文件路径       /// 根节点名称       /// 节点的子节点名称       /// 节点的子节点原始内容       /// 节点的子节点新内容       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;           }       }

登录后复制

///         /// 修改节点属性值操作        ///         /// xml文件路径        /// 根节点名称,如:bookstore        /// 节点属性名        /// 节点属性原来值        /// 节点属性修改后的值        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;            }        }

登录后复制

///         /// 插入节点操作        ///         /// xml文件路径        /// 根节点名称,如:bookstore        /// 节点名称,如:book        /// 节点的属性-属性值集合        /// 节点子节点名称-内容        public void InsertNode(string path, string rootNode, string node, Dictionary         nodeAttributes, Dictionary 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);//添加到节点中                    }                }                root.AppendChild(xe1);                SaveXml(path);            }            catch (Exception)            {                 throw;            }        }

登录后复制

调用:

string path = Server.MapPath("Books.xml");           XmlHelper xHelper = new XmlHelper(path);           /*插入*/           //Dictionary dc1 = new Dictionary();           //dc1.Add("genre", "李赞红");           //dc1.Add("ISBN", "2-3631-4");           //Dictionary dc2 = new Dictionary();           //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 

调用:

//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 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 list = new List { new Person { Name = "Xuj", Age = 20 }, new Person { Name = "duj", Age = 20 }, new Person { Name = "fuj", Age = 20 } };            string s = CXmlSerializer>.Serialize(list);

登录后复制

以上就是详细介绍xml的使用方法总结的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2418987.html

(0)
上一篇 2025年3月3日 02:33:12
下一篇 2025年2月18日 02:39:50

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论