C# 遍历XML文件,添加,更新,删除节点

一,将XML文件添加到text文本中:

方法1,最简单方式

 1 private void ReadFile()        

 2 

 3  { 

 4 

 5     string path =  Application.StartupPath + @"/bookstore.xml";

 6 

 7             byte[] myByte;

 8 

 9              //File.OpenRead(path);

10 

11              myByte = File.ReadAllBytes(path);

12 

13             this.textBox1.Text = string.Empty; 

14 

15             //this.textBox1.Text = new UnicodeEncoding().GetString(myByte);

16 

17              this.textBox1.Text = Encoding.UTF8.GetString(myByte);         

18 

19 }

方法2,通过分析节点遍历XML添加

 

  1 private void Updata()         

  2 

  3 { 

  4 

  5             XmlReader reader = null; 

  6 

  7             try

  8 

  9              { 

 10 

 11                 // 创建XmlReaderSettings对象 

 12 

 13                 XmlReaderSettings settings = new XmlReaderSettings();

 14 

 15                  // 设置XmlReaderSettings对象的属性

 16 

 17                  settings.ProhibitDtd = false;

 18 

 19                  //settings.DtdProcessing = System.Xml.DtdProcessing.Ignore;

 20 

 21                  // 使用XmlReaderSettings对象来创建XmlReader对象 

 22 

 23                 reader = XmlReader.Create(path, settings);

 24 

 25                 ReadXml(reader);

 26 

 27              }  

 28 

 29            catch (Exception ex) 

 30 

 31             { 

 32 

 33                 MessageBox.Show(ex.Message);

 34 

 35              }

 36 

 37              finally

 38 

 39              {

 40 

 41                  if (reader != null)

 42 

 43                      reader.Close();

 44 

 45              } 

 46 

 47         }

 48 

 49         //按节点分析读取

 50 

 51          private void ReadXml(XmlReader reader)

 52 

 53          {

 54 

 55              this.textBox1.Text = string.Empty;

 56 

 57              try 

 58 

 59             { 

 60 

 61                 // 解析文件,并显示每一个节点 

 62 

 63                 while (reader.Read())  

 64 

 65                {

 66 

 67                      switch (reader.NodeType)

 68 

 69                      {  

 70 

 71                        case XmlNodeType.Element: 

 72 

 73                             if (reader.IsEmptyElement) // 空元素?

 74 

 75                              { 

 76 

 77                                 this.textBox1.Text += "<"+ reader.Name + "/>"+"\r\n"; 

 78 

 79                             } 

 80 

 81                             else

 82 

 83                              { 

 84 

 85                                 if (reader.HasAttributes)   // 属性?

 86 

 87                                  { 

 88 

 89                                     this.textBox1.Text += "<" + reader.Name + " ";

 90 

 91                                      while (reader.MoveToNextAttribute()) 

 92 

 93                                     {

 94 

 95                                          this.textBox1.Text += reader.Name + "=\"" + reader.Value + "\"";

 96 

 97                                      }

 98 

 99                                      this.textBox1.Text += ">\r\n";

100 

101                                  } 

102 

103                                 else 

104 

105                                     this.textBox1.Text += "<" + reader.Name + ">"+"\r\n"; 

106 

107                             } 

108 

109                             break; 

110 

111                         case XmlNodeType.Text: 

112 

113                             this.textBox1.Text += reader.Value + "\r\n"; 

114 

115                             break;

116 

117                          case XmlNodeType.CDATA:

118 

119                              this.textBox1.Text += "<![CDATA[" + reader.Value + "]]>" + "\r\n";

120 

121                              break;

122 

123                          case XmlNodeType.ProcessingInstruction:

124 

125                              this.textBox1.Text += "<?" + reader.Name + " " + reader.Value + "?>" + "\r\n";

126 

127                              break;

128 

129                          case XmlNodeType.Comment:

130 

131                              this.textBox1.Text += "<!--" + reader.Value + "-->" + "\r\n";

132 

133                              break;

134 

135                          case XmlNodeType.XmlDeclaration:

136 

137                              this.textBox1.Text += "<?xml version='1.0'?>" + "\r\n";

138 

139                              break;

140 

141                          case XmlNodeType.Document:

142 

143                              break;

144 

145                          case XmlNodeType.DocumentType:

146 

147                              this.textBox1.Text += "<!DOCTYE " + reader.Name + " [" + reader.Value + "]>" + "\r\n"; 

148 

149                             break;

150 

151                          case XmlNodeType.EntityReference:

152 

153                              this.textBox1.Text += reader.Name + "\r\n"; 

154 

155                             break;

156 

157                          case XmlNodeType.EndElement:

158 

159                              this.textBox1.Text += "</" + reader.Name + ">" + "\r\n"; 

160 

161                             break;

162 

163                      } 

164 

165                 } 

166 

167             } 

168 

169             catch (XmlException ex)

170 

171              {

172 

173                  MessageBox.Show(ex.Message);

174 

175              }

176 

177          }

方法3,读取子节点

 1  //读取子节点

 2         private void UpdataXML()

 3         {

 4             XmlNode xn = xmlDoc.SelectSingleNode("bookstore");

 5 

 6             XmlNodeList xnl = xn.ChildNodes;

 7 

 8             this.textBox1.Text = string.Empty;

 9 

10             foreach (XmlNode xnf in xnl)

11             {

12                 XmlElement xe = (XmlElement)xnf;

13                 //Console.WriteLine(xe.GetAttribute("genre"));//显示属性值

14                 //Console.WriteLine(xe.GetAttribute("ISBN"));

15                 XmlNodeList xnf1 = xe.ChildNodes;

16                 foreach (XmlNode xn2 in xnf1)

17                 {

18                     //Console.WriteLine(xn2.InnerText);//显示子节点点文本

19                     this.textBox1.Text += xn2.InnerText + "\r\n";

20                 }

21             }

22         }

二,将XML添加到treeView控件中

 1  

 2             private XmlDocument xmlDoc;

 3             string path = Application.StartupPath + @"/bookstore.xml";

 4             xmlDoc = new XmlDocument();

 5             xmlDoc.Load(path);

 6             treeViewXML.Nodes.Clear();

 7             XmlNode stu = xmlDoc.DocumentElement;

 8             foreach (XmlNode node in stu.ChildNodes)

 9             {

10                 TreeNode studentNode;

11                 studentNode = treeViewXML.Nodes.Add(node.Name);

12                 foreach (XmlNode nodes in node.ChildNodes)

13                 {

14                     studentNode.Nodes.Add(nodes.InnerText);

15                 }

16             }

三,创建XML文件

在C#.net中如何操作XML 需要添加的命名空间: using System.Xml;

定义几个公共对象: XmlDocument xmldoc ; XmlNode xmlnode ; XmlElement xmlelem ;

1,创建到服务器同名目录下的xml文件:

 1 //方法一:

 2 xmldoc = new XmlDocument ( ) ;

 3 //加入XML的声明段落,<?xml version="1.0" encoding="gb2312"?>

 4 XmlDeclaration xmldecl;

 5  xmldecl = xmldoc.CreateXmlDeclaration("1.0","gb2312",null);

 6  xmldoc.AppendChild ( xmldecl);

 7 

 8 //加入一个根元素

 9 xmlelem = xmldoc.CreateElement ( "" , "Employees" , "" ) ;

10 xmldoc.AppendChild ( xmlelem ) ;

11 //加入另外一个元素

12 for(int i=1;i<3;i++)

13 {

14 

15 XmlNode root=xmldoc.SelectSingleNode("Employees");//查找<Employees> 

16 XmlElement xe1=xmldoc.CreateElement("Node");//创建一个<Node>节点 

17 xe1.SetAttribute("genre","李赞红");//设置该节点genre属性 

18 xe1.SetAttribute("ISBN","2-3631-4");//设置该节点ISBN属性

19 

20 XmlElement xesub1=xmldoc.CreateElement("title"); 

21 xesub1.InnerText="CS从入门到精通";//设置文本节点 

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

23 XmlElement xesub2=xmldoc.CreateElement("author"); 

24 xesub2.InnerText="候捷"; 

25 xe1.AppendChild(xesub2); 

26 XmlElement xesub3=xmldoc.CreateElement("price"); 

27 xesub3.InnerText="58.3"; 

28 xe1.AppendChild(xesub3);

29 

30 root.AppendChild(xe1);//添加到<Employees>节点中 

31 }

32 //保存创建好的XML文档

33 xmldoc.Save ( Server.MapPath("data.xml") ) ;

//////////////////////////////////////////////////////////////////////////////////////
结果:在同名目录下生成了名为data.xml的文件,内容如下,
<?xml version="1.0" encoding="gb2312"?>
<Employees>
  <Node genre="李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </Node>
  <Node genre="李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </Node>
</Employees>

 

 1 方法二:

 2 XmlTextWriter xmlWriter;

 3    string strFilename = Server.MapPath("data1.xml") ;

 4 

 5    xmlWriter = new XmlTextWriter(strFilename,Encoding.Default);//创建一个xml文档

 6    xmlWriter.Formatting = Formatting.Indented;

 7    xmlWriter.WriteStartDocument();

 8    xmlWriter.WriteStartElement("Employees");

 9 

10    xmlWriter.WriteStartElement("Node");

11    xmlWriter.WriteAttributeString("genre","李赞红");

12    xmlWriter.WriteAttributeString("ISBN","2-3631-4");

13 

14    xmlWriter.WriteStartElement("title");

15    xmlWriter.WriteString("CS从入门到精通");

16    xmlWriter.WriteEndElement();

17 

18    xmlWriter.WriteStartElement("author");

19    xmlWriter.WriteString("候捷");

20    xmlWriter.WriteEndElement();

21 

22    xmlWriter.WriteStartElement("price");

23    xmlWriter.WriteString("58.3");

24    xmlWriter.WriteEndElement();

25 

26    xmlWriter.WriteEndElement();

27 

28    xmlWriter.Close();

29 //////////////////////////////////////////////////////////////////////////////////////

结果:
<?xml version="1.0" encoding="gb2312"?>
<Employees>
  <Node genre="李赞红" ISBN="2-3631-4">
    <title>CS从入门到精通</title>
    <author>候捷</author>
    <price>58.3</price>
  </Node>
</Employees>


四,添加节点

 1             XmlNode root = xmlDoc.SelectSingleNode("bookstore");//查找<bookstore>

 2             XmlElement xe1 = xmlDoc.CreateElement("book");//创建一个<book>节点

 3             xe1.SetAttribute("genre", "李赞红");//设置该节点genre属性

 4             xe1.SetAttribute("ISBN", "2-3631-4");//设置该节点ISBN属性

 5 

 6             XmlElement xesub1 = xmlDoc.CreateElement("title");

 7             xesub1.InnerText = "CS从入门到精通";//设置文本节点

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

 9 

10             XmlElement xesub2 = xmlDoc.CreateElement("author");

11             xesub2.InnerText = "候捷";

12             xe1.AppendChild(xesub2);

13             XmlElement xesub3 = xmlDoc.CreateElement("price");

14             xesub3.InnerText = "58.3";

15             xe1.AppendChild(xesub3);

16 

17             root.AppendChild(xe1);//添加到<bookstore>节点中

18             xmlDoc.Save("bookstore.xml");

五,更新节点

 1                   XmlNodeList nodeList = xmlDoc.SelectSingleNode("bookstore").ChildNodes;//获取bookstore节点的所有子节点

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

 3             {

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

 5                 if (xe.GetAttribute("genre") == "李赞红")//如果genre属性值为“李赞红”

 6                 {

 7                     xe.SetAttribute("genre", "林芳");//则修改该属性为“update李赞红”

 8 

 9                     XmlNodeList nls = xe.ChildNodes;//继续获取xe子节点的所有子节点

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

11                     {

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

13                         if (xe2.Name == "author")//如果找到

14                         {

15                             xe2.InnerText = "李胜";//则修改

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

17                         }

18                     }

19                     break;

20                 }

21             }

22 

23             xmlDoc.Save("bookstore.xml");//保存。

六,删除节点

 1             private bool first,second;            

 2             XmlNodeList xnl = xmlDoc.SelectSingleNode("bookstore").ChildNodes;

 3             foreach (XmlNode xn in xnl)

 4             {

 5                 XmlElement xe = (XmlElement)xn;

 6                 if (xe.GetAttribute("genre") == "fantasy")

 7                 {

 8                     xe.RemoveAttribute("genre");//删除genre属性

 9                     first = true;

10                 }

11                 else if (xe.GetAttribute("genre") == "林芳")

12                 {

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

14                     second = true;

15                 }

16                 if (first && second)

17                     break;

18             }

19             xmlDoc.Save("bookstore.xml");

 

你可能感兴趣的:(xml)