C# 实现对XML的基本操作(创建xml文件,增、删、改、查 xml节点信息)

 XML文件在存储、交换和传输数据信息上有着很方便处理,那么今天这篇文章主要讲一下用C#如何实现对XML文件的基本操作,如:创建xml文件,增、删、改、查xml的节点信息。所使用的方法很基础,方便易懂。

  本文的主要模块为:

    ① :生成xml文件

    ② :遍历xml文件的节点信息

    ③ :修改xml文件的节点信息

    ④ :向xml文件添加节点信息

    ⑤ :删除指定xml文件的节点信息


  • 假设我们需要设计出这样的一个xml文件来存储相应的信息,如下所示:

 


  
    Lenovo
    5000
  
  
    IBM
    10000
  
  生成这样的一个xml文件请看下述C#代码:
view source print ?
01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Text;
05 using System.Xml;
06   
07 namespace OperateXML
08 {
09     class Program
10     {
11         static void Main(string[] args)
12         {
13             try
14             {
15                 //xml文件存储路径
16                 string myXMLFilePath = "E://MyComputers.xml";
17                 //生成xml文件
18                 GenerateXMLFile(myXMLFilePath);
19             }
20             catch (Exception ex)
21             {
22                 Console.WriteLine(ex.ToString());
23             }
24         }
25   
26         private static void GenerateXMLFile(string xmlFilePath)
27         {
28             try
29             {
30                 //初始化一个xml实例
31                 XmlDocument myXmlDoc = new XmlDocument();
32                 //创建xml的根节点
33                 XmlElement rootElement = myXmlDoc.CreateElement("Computers");
34                 //将根节点加入到xml文件中(AppendChild)
35                 myXmlDoc.AppendChild(rootElement);
36   
37                 //初始化第一层的第一个子节点
38                 XmlElement firstLevelElement1 = myXmlDoc.CreateElement("Computer");
39                 //填充第一层的第一个子节点的属性值(SetAttribute)
40                 firstLevelElement1.SetAttribute("ID", "11111111");
41                 firstLevelElement1.SetAttribute("Description", "Made in China");
42                 //将第一层的第一个子节点加入到根节点下
43                 rootElement.AppendChild(firstLevelElement1);
44                 //初始化第二层的第一个子节点
45                 XmlElement secondLevelElement11 = myXmlDoc.CreateElement("name");
46                 //填充第二层的第一个子节点的值(InnerText)
47                 secondLevelElement11.InnerText = "Lenovo";
48                 firstLevelElement1.AppendChild(secondLevelElement11);
49                 XmlElement secondLevelElement12 = myXmlDoc.CreateElement("price");
50                 secondLevelElement12.InnerText = "5000";
51                 firstLevelElement1.AppendChild(secondLevelElement12);
52   
53   
54                 XmlElement firstLevelElement2 = myXmlDoc.CreateElement("Computer");
55                 firstLevelElement2.SetAttribute("ID", "2222222");
56                 firstLevelElement2.SetAttribute("Description", "Made in USA");
57                 rootElement.AppendChild(firstLevelElement2);
58                 XmlElement secondLevelElement21 = myXmlDoc.CreateElement("name");
59                 secondLevelElement21.InnerText = "IBM";
60                 firstLevelElement2.AppendChild(secondLevelElement21);
61                 XmlElement secondLevelElement22 = myXmlDoc.CreateElement("price");
62                 secondLevelElement22.InnerText = "10000";
63                 firstLevelElement2.AppendChild(secondLevelElement22);
64   
65                 //将xml文件保存到指定的路径下
66                 myXmlDoc.Save(xmlFilePath);
67             }
68             catch (Exception ex)
69             {
70                 Console.WriteLine(ex.ToString());
71             }
72         }
73     }
74 }

 

  运行这样一段代码就可以在E盘中生成相应的xml文件Computers.xml,这个方法显得比较笨拙,但是很实在,基础好用~~

  • 知道怎么生成xml文件之后,下一步就要了解:如何读取xml文件(即:遍历xml文件的节点信息)
  下面的这段代码实现了对xml文件节点信息的读取,代码有详细的注解,在此不过多解释。代码如下:
view source print ?
01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Text;
05 using System.Xml;
06   
07 namespace OperateXML
08 {
09     class Program
10     {
11         static void Main(string[] args)
12         {
13             try
14             {
15                 //xml文件存储路径
16                 string myXMLFilePath = "E://MyComputers.xml";
17                 //遍历xml文件的信息
18                 GetXMLInformation(myXMLFilePath);
19             }
20             catch (Exception ex)
21             {
22                 Console.WriteLine(ex.ToString());
23             }
24         }
25   
26         private static void GetXMLInformation(string xmlFilePath)
27         {
28             try
29             {
30                 //初始化一个xml实例
31                 XmlDocument myXmlDoc = new XmlDocument();
32                 //加载xml文件(参数为xml文件的路径)
33                 myXmlDoc.Load(xmlFilePath);
34                 //获得第一个姓名匹配的节点(SelectSingleNode):此xml文件的根节点
35                 XmlNode rootNode = myXmlDoc.SelectSingleNode("Computers");
36                 //分别获得该节点的InnerXml和OuterXml信息
37                 string innerXmlInfo = rootNode.InnerXml.ToString();
38                 string outerXmlInfo = rootNode.OuterXml.ToString();
39                 //获得该节点的子节点(即:该节点的第一层子节点)
40                 XmlNodeList firstLevelNodeList = rootNode.ChildNodes;
41                 foreach (XmlNode node in firstLevelNodeList)
42                 {
43                     //获得该节点的属性集合
44                     XmlAttributeCollection attributeCol = node.Attributes;
45                     foreach (XmlAttribute attri in attributeCol)
46                     {
47                         //获取属性名称与属性值
48                         string name = attri.Name;
49                         string value = attri.Value;
50                         Console.WriteLine("{0} = {1}", name, value);
51                     }
52   
53                     //判断此节点是否还有子节点
54                     if (node.HasChildNodes)
55                     {
56                         //获取该节点的第一个子节点
57                         XmlNode secondLevelNode1 = node.FirstChild;
58                         //获取该节点的名字
59                         string name = secondLevelNode1.Name;
60                         //获取该节点的值(即:InnerText)
61                         string innerText = secondLevelNode1.InnerText;
62                         Console.WriteLine("{0} = {1}", name, innerText);
63   
64                         //获取该节点的第二个子节点(用数组下标获取)
65                         XmlNode secondLevelNode2 = node.ChildNodes[1];
66                         name = secondLevelNode2.Name;
67                         innerText = secondLevelNode2.InnerText;
68                         Console.WriteLine("{0} = {1}", name, innerText);
69                     }
70                 }
71             }
72             catch (Exception ex)
73             {
74                 Console.WriteLine(ex.ToString());
75             }
76         }
77     }
78 }

  这里要强调一点:XmlElement是XmlNode的继承,所以XmlElement可以调用更加多的方法,实现相应的功能。

  • 接下来要实现对xml文件节点信息的修改
  假设我们要修改上面刚刚生成的xml文件的这条信息
                改成
  请看如下代码实现方案:
view source print ?
01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Text;
05 using System.Xml;
06   
07 namespace OperateXML
08 {
09     class Program
10     {
11         static void Main(string[] args)
12         {
13             try
14             {
15                 //xml文件存储路径
16                 string myXMLFilePath = "E://MyComputers.xml";
17                 //修改xml文件的节点信息
18                 ModifyXmlInformation(myXMLFilePath);
19             }
20             catch (Exception ex)
21             {
22                 Console.WriteLine(ex.ToString());
23             }
24         }
25   
26         private static void ModifyXmlInformation(string xmlFilePath)
27         {
28             try
29             {
30                 XmlDocument myXmlDoc = new XmlDocument();
31                 myXmlDoc.Load(xmlFilePath);
32                 XmlNode rootNode = myXmlDoc.FirstChild;
33                 XmlNodeList firstLevelNodeList = rootNode.ChildNodes;
34                 foreach (XmlNode node in firstLevelNodeList)
35                 {
36                     //修改此节点的属性值
37                     if (node.Attributes["Description"].Value.Equals("Made in USA", StringComparison.InvariantCultureIgnoreCase))
38                     {
39                         node.Attributes["Description"].Value = "Made in HongKong";
40                     }
41                 }
42                 //要想使对xml文件所做的修改生效,必须执行以下Save方法
43                 myXmlDoc.Save(xmlFilePath);
44             }
45             catch (Exception ex)
46             {
47                 Console.WriteLine(ex.ToString());
48             }
49   
50         }
51   
52     }
53 }

  运行上面这段代码,就可以实现预期的更改,代码很好理解,在此不过多啰嗦。

  • 下面实现向xml文件中的相应位置插入节点信息
  假设我们想通过插入节点将原来的xml文件结构变成如下所示
  < Computers >
  < Computer ID =" 11111111 " Description =" Made in China " >
       < name > Lenovo name >
     < price > 5000 price >
       < color IsMixed =" Yes " > black color >
   Computer >
   < Computer ID =" 2222222 " Description =" Made in USA " >
       < name > IBM name >
     < price > 10000 price >
     < color IsMixed =" Yes " > black color >
   Computer >
    Computers >
  
  代码如下所示:
view source print ?
01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Text;
05 using System.Xml;
06   
07 namespace OperateXML
08 {
09     class Program
10     {
11         static void Main(string[] args)
12         {
13             try
14             {
15                 //xml文件存储路径
16                 string myXMLFilePath = "E://MyComputers.xml";
17                 //向xml文件添加节点信息
18                 AddXmlInformation(myXMLFilePath);
19             }
20             catch (Exception ex)
21             {
22                 Console.WriteLine(ex.ToString());
23             }
24         }
25   
26         private static void AddXmlInformation(string xmlFilePath)
27         {
28             try
29             {
30                 XmlDocument myXmlDoc = new XmlDocument();
31                 myXmlDoc.Load(xmlFilePath);
32                 //添加一个带有属性的节点信息
33                 foreach (XmlNode node in myXmlDoc.FirstChild.ChildNodes)
34                 {
35                     XmlElement newElement = myXmlDoc.CreateElement("color");
36                     newElement.InnerText = "black";
37                     newElement.SetAttribute("IsMixed", "Yes");
38                     node.AppendChild(newElement);
39                 }
40                 //保存更改
41                 myXmlDoc.Save(xmlFilePath);
42             }
43             catch (Exception ex)
44             {
45                 Console.WriteLine(ex.ToString());
46             }
47         }
48   
49     }
50 }

  
  • 下面实现删除指定xml文件节点信息(即:将刚刚添加上的节点删除掉)代码如下:
view source print ?
01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Text;
05 using System.Xml;
06   
07 namespace OperateXML
08 {
09     class Program
10     {
11         static void Main(string[] args)
12         {
13             try
14             {
15                 //xml文件存储路径
16                 string myXMLFilePath = "E://MyComputers.xml";
17                 //删除xml文件节点信息
18                 DeleteXmlInformation(myXMLFilePath);
19             }
20             catch (Exception ex)
21             {
22                 Console.WriteLine(ex.ToString());
23             }
24         }
25   
26         private static void DeleteXmlInformation(string xmlFilePath)
27         {
28             try
29             {
30                 XmlDocument myXmlDoc = new XmlDocument();
31                 myXmlDoc.Load(xmlFilePath);
32                 foreach (XmlNode node in myXmlDoc.FirstChild.ChildNodes)
33                 {
34                     //记录该节点下的最后一个子节点(简称:最后子节点)
35                     XmlNode lastNode = node.LastChild;
36                     //删除最后子节点下的左右子节点
37                     lastNode.RemoveAll();
38                     //删除最后子节点
39                     node.RemoveChild(lastNode);
40                 }
41                 //保存对xml文件所做的修改
42                 myXmlDoc.Save(xmlFilePath);
43             }
44             catch (Exception ex)
45             {
46                 Console.WriteLine(ex.ToString());
47             }
48         }
49   
50     }
51 }
  
  运行上段代码之后就可以实现对相应节点的删除。

你可能感兴趣的:(.NET)