xml使用系统整理

1、 认识xml

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

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

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

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

3、对xml文档增删改查

 1  //声明一个XmlDocument空对象

 2         protected XmlDocument XmlDoc = new XmlDocument();

 3         /// <summary>

 4         /// 构造函数,导入xml文件

 5         /// </summary>

 6         /// <param name="path"></param>

 7         public XmlHelper(string path)

 8         {

 9             try

10             {

11                 XmlDoc.Load(path);

12             }

13             catch (Exception ex)

14             {

15                 throw ex;

16             }

17         }

18         /// <summary>

19         /// 保存文件

20         /// </summary>

21         /// <param name="path"></param>

22         public void SaveXml(string path)

23         {

24             try

25             {

26                 XmlDoc.Save(path);

27             }

28             catch (System.Exception ex)

29             {

30                 throw ex;

31             }

32         }
 1  /// <summary>

 2         /// 获取节点的子节点的内容

 3         /// </summary>

 4         /// <param name="path"></param>

 5         /// <param name="rootNode"></param>

 6         /// <param name="attributeName"></param>

 7         /// <returns></returns>

 8         public string GetNodeChildAttribute(string path, string rootNode, string attributeName)

 9         {

10             XmlNode xn = XmlDoc.SelectSingleNode(rootNode);

11             StringBuilder sb = new StringBuilder();

12             XmlNodeList xnl = xn.ChildNodes;

13 

14             foreach (XmlNode xnf in xnl)

15             {

16                 XmlElement xe = (XmlElement)xnf;

17                 XmlNodeList xnf1 = xe.ChildNodes;

18                 foreach (XmlNode xn2 in xnf1)

19                 {

20                     if (xn2.Name == attributeName)

21                     {

22                         sb.Append(xn2.InnerText);//显示子节点点文本

23                     }

24                 }

25             }

26             return sb.ToString();

27         }
 1 /// <summary>

 2         /// 获取节点的属性值

 3         /// </summary>

 4         /// <param name="path">xml路径</param>

 5         /// <param name="rootNode">根节点名称</param>

 6         /// <param name="attributeName">属性名称</param>

 7         /// <returns></returns>

 8         public string GetNodeAttribute(string path, string rootNode, string attributeName)

 9         {

10             try

11             {

12                 XmlNode xn = XmlDoc.SelectSingleNode(rootNode);

13                 XmlNodeList xnl = xn.ChildNodes;

14                 StringBuilder sb = new StringBuilder();

15                 foreach (XmlNode xnf in xnl)

16                 {

17                     XmlElement xe = (XmlElement)xnf;

18                     sb.Append(xe.GetAttribute(attributeName));

19                 }

20                 return sb.ToString();

21             }

22             catch (Exception)

23             {

24 

25                 throw;

26             }

27         }
 1  /// <summary>

 2         /// 删除节点/节点属性

 3         /// </summary>

 4         /// <param name="path">xml文件地址</param>

 5         /// <param name="rootNode">根节点名称</param>

 6         /// <param name="delNode">要删除的节点</param>

 7         /// <param name="attributeName">节点属性</param>

 8         /// <param name="attributeValue">属性值</param>

 9         public void DeleteNode(string path, string rootNode, string attributeName, string attributeValue)

10         {

11             try

12             {

13                 XmlNodeList xnl = XmlDoc.SelectSingleNode(rootNode).ChildNodes;

14                 foreach (XmlNode xn in xnl)

15                 {

16                     XmlElement xe = (XmlElement)xn;

17                     if (xe.GetAttribute(attributeName) == attributeValue)

18                     {

19                         //xe.RemoveAttribute(attributeName);//删除属性

20                         xe.RemoveAll();//删除该节点的全部内容

21                     }

22                 }

23                 SaveXml(path);

24             }

25             catch (Exception)

26             {

27 

28                 throw;

29             }

30         }
 1  /// <summary>

 2         /// 修改节点的子节点内容

 3         /// </summary>

 4         /// <param name="path">xml文件路径</param>

 5         /// <param name="rootNode">根节点名称</param>

 6         /// <param name="attributeName">节点的子节点名称</param>

 7         /// <param name="attributeOldValue">节点的子节点原始内容</param>

 8         /// <param name="attributeNewValue">节点的子节点新内容</param>

 9         public void UpdateChildNodeAttribute(string path, string rootNode, string attributeName, string attributeOldValue, string attributeNewValue)

10         {

11             try

12             {

13                 XmlNodeList nodeList = XmlDoc.SelectSingleNode(rootNode).ChildNodes;//获取根节点的所有子节点

14                 foreach (XmlNode xn in nodeList)//遍历所有子节点

15                 {

16                     XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型

17                     if (string.IsNullOrEmpty(attributeName) || string.IsNullOrEmpty(attributeOldValue))

18                     {

19                         return;

20                     }

21                     else

22                     {

23                         XmlNodeList nls = xe.ChildNodes;

24                         if (nls != null && nls.Count > 0)

25                         {

26                             foreach (XmlNode xn1 in nls)//遍历

27                             {

28                                 XmlElement xe2 = (XmlElement)xn1;//转换类型

29                                 if (xe2.InnerText == attributeOldValue)//如果找到

30                                 {

31                                     xe2.InnerText = attributeNewValue;//则修改

32                                     break;//找到退出来就可以了

33                                 }

34                             }

35                         }

36                     }

37                 }

38                 SaveXml(path);

39             }

40             catch (Exception)

41             {

42 

43                 throw;

44             }

45         }
 1 /// <summary>

 2         /// 修改节点属性值操作

 3         /// </summary>

 4         /// <param name="path">xml文件路径</param>

 5         /// <param name="rootNode">根节点名称,如:bookstore</param>

 6         /// <param name="attributeName">节点属性名</param>

 7         /// <param name="attributeOldValue">节点属性原来值</param>

 8         /// <param name="attributeNewValue">节点属性修改后的值</param>

 9         public void UpdateNodeAttribute(string path, string rootNode, string attributeName, string attributeOldValue, string attributeNewValue)

10         {

11             try

12             {

13                 XmlNodeList nodeList = XmlDoc.SelectSingleNode(rootNode).ChildNodes;//获取根节点的所有子节点

14                 foreach (XmlNode xn in nodeList)//遍历所有子节点

15                 {

16                     XmlElement xe = (XmlElement)xn;//将子节点类型专程xmlelement类型

17                     if (string.IsNullOrEmpty(attributeName) || string.IsNullOrEmpty(attributeOldValue))

18                     {

19                         return;

20                     }

21                     else

22                     {

23                         if (xe.GetAttribute(attributeName) == attributeOldValue)

24                         {

25                             xe.SetAttribute(attributeName, attributeNewValue);

26                         }

27                     }

28                 }

29                 SaveXml(path);

30             }

31             catch (Exception)

32             {

33 

34                 throw;

35             }

36         }
 1 /// <summary>

 2         /// 插入节点操作

 3         /// </summary>

 4         /// <param name="path">xml文件路径</param>

 5         /// <param name="rootNode">根节点名称,如:bookstore</param>

 6         /// <param name="node">节点名称,如:book</param>

 7         /// <param name="nodeAttributes">节点的属性-属性值集合</param>

 8         /// <param name="childAttributes">节点子节点名称-内容</param>

 9         public void InsertNode(string path, string rootNode, string node, Dictionary<string, string> nodeAttributes, Dictionary<string, string> childAttributes)

10         {

11             try

12             {

13                 XmlNode root = XmlDoc.SelectSingleNode(rootNode);//找到根节点bookstore

14                 XmlElement xe1 = XmlDoc.CreateElement(node);//创建子节点book

15                 if (nodeAttributes != null && nodeAttributes.Count > 0)

16                 {

17                     foreach (var n in nodeAttributes)

18                     {

19                         xe1.SetAttribute(n.Key, n.Value);

20                     }

21                 }

22                 if (childAttributes != null && childAttributes.Count > 0)

23                 {

24                     XmlElement xesub1;

25                     foreach (var n in childAttributes)

26                     {

27                         xesub1 = XmlDoc.CreateElement(n.Key);

28                         xesub1.InnerText = n.Value;

29                         xe1.AppendChild(xesub1);//添加到<book>节点中

30                     }

31                 }

32                 root.AppendChild(xe1);

33                 SaveXml(path);

34             }

35             catch (Exception)

36             {

37 

38                 throw;

39             }

40         }

调用:

 1  string path = Server.MapPath("Books.xml");

 2             XmlHelper xHelper = new XmlHelper(path);

 3             /*插入*/

 4             //Dictionary<string, string> dc1 = new Dictionary<string, string>();

 5             //dc1.Add("genre", "李赞红");

 6             //dc1.Add("ISBN", "2-3631-4");

 7             //Dictionary<strin插入g, string> dc2 = new Dictionary<string, string>();

 8             //dc2.Add("title", "CS从入门到精通");

 9             //dc2.Add("author", "候捷");

10             //dc2.Add("price", "58.3");

11             //xHelper.InsertNode(path, "bookstore", "book", dc1, dc2);

12 

13             /*修改*/

14             //xHelper.UpdateNodeAttribute(path, "bookstore", "genre", "李赞红", "李");

15             //xHelper.UpdateChildNodeAttribute(path, "bookstore", "title", "CS从入门到精通", "cs");

16 

17             /*删除节点*/

18             //xHelper.DeleteNode(path, "bookstore", "genre", "李");

19 

20             //Response.Write(xHelper.GetNodeAttribute(path, "bookstore", "genre"));

21             //Response.Write(xHelper.GetNodeChildAttribute(path, "bookstore", "price"));

4、通过xml数据绑定

xml转DataTable

 
   
 1  public DataTable XmlToData(string path, string rootNode, params string[] columns)

 2         {

 3             DataTable dt = new DataTable();

 4             XmlNodeList xn = XmlDoc.SelectSingleNode(rootNode).ChildNodes;

 5             try

 6             {

 7                 if (columns.Length > 0)

 8                 {

 9                     DataColumn dc;

10                     for (int i = 0; i < columns.Length; i++)

11                     {

12                         dc = new DataColumn(columns[i]);

13                         dt.Columns.Add(dc);

14                     }

15                     foreach (XmlNode xnf in xn)

16                     {

17                         XmlElement xe = (XmlElement)xnf;

18                         XmlNodeList xnf1 = xe.ChildNodes;

19                         int i = 0;

20                         DataRow dr = dt.NewRow();

21                         foreach (XmlNode xn2 in xnf1)

22                         {

23                             dr[i] = xn2.InnerText;

24                             i++;

25                         }

26                         dt.Rows.Add(dr);

27                     }

28                 }

29             }

30             catch (Exception)

31             {

32 

33                 throw;

34             }

35             return dt;

36 

37         }
 
  

调用:

1  //string[] arr = { "title", "author", "price" };

2             //GridView1.DataSource = xHelper.XmlToData(path, "bookstore", arr);

3             //GridView1.DataBind();

DataTable转xml

 1  /*datatable转xml*/

 2         public  string DataTableToXml(DataTable dt)

 3         {

 4             if (dt != null)

 5             {

 6                 MemoryStream ms = null;

 7                 XmlTextWriter XmlWt = null;

 8                 try

 9                 {

10                     ms = new MemoryStream();

11                     //根据ms实例化XmlWt

12                     XmlWt = new XmlTextWriter(ms, Encoding.Unicode);

13                     //获取ds中的数据

14                     dt.WriteXml(XmlWt);

15                     int count = (int)ms.Length;

16                     byte[] temp = new byte[count];

17                     ms.Seek(0, SeekOrigin.Begin);

18                     ms.Read(temp, 0, count);

19                     //返回Unicode编码的文本

20                     UnicodeEncoding ucode = new UnicodeEncoding();

21                     string returnValue = ucode.GetString(temp).Trim();

22                     return returnValue;

23                 }

24                 catch (System.Exception ex)

25                 {

26                     throw ex;

27                 }

28                 finally

29                 {

30                     //释放资源

31                     if (XmlWt != null)

32                     {

33                         XmlWt.Close();

34                         ms.Close();

35                         ms.Dispose();

36                     }

37                 }

38             }

39             else

40             {

41                 return "";

42             }

43         }

调用:

1  //bool s = xHelper.CDataToXmlFile(xHelper.XmlToData(path, "bookstore", arr), "Bookss.xml","book");

5、xml序列化反序列化

1  [Serializable]

2     public class Person

3     {

4         public string Name { get; set; }

5         public int Age { get; set; }

6     }
 1 public class CXmlSerializer<T> where T : new()

 2     {

 3         private static XmlSerializer _Serializer = new XmlSerializer(typeof(T));

 4 

 5         public static string Serialize(T t)

 6         {

 7             string s = "";

 8             using (MemoryStream ms = new MemoryStream())

 9             {

10                 _Serializer.Serialize(ms, t);

11                 s = System.Text.UTF8Encoding.UTF8.GetString(ms.ToArray());

12             }

13             return s;

14         }

15 

16         public static T Deserialize(string s)

17         {

18             T t;

19             using (MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(s)))

20             {

21                 t = (T)_Serializer.Deserialize(ms);

22             }

23             return t;

24         }

25     }

调用:

1 List<Person> list = new List<Person> { new Person { Name = "Xuj", Age = 20 }, new Person { Name = "duj", Age = 20 }, new Person { Name = "fuj", Age = 20 } };

2             string s = CXmlSerializer<List<Person>>.Serialize(list);

 

你可能感兴趣的:(xml)