1.XmlTextReader读XML文件

 

  1. protected void Page_Load(object sender, EventArgs e) 
  2.     string xmlFile = Server.MapPath("films.xml"); 
  3.     XmlTextReader reader = new XmlTextReader(xmlFile); 
  4.     while (reader.Read()) 
  5.     { 
  6.         if (reader.NodeType == XmlNodeType.Element) 
  7.         { 
  8.             if (reader.Name == "title"
  9.             { 
  10.                 Response.Write("<b>名称:</b>" + reader.ReadString()); 
  11.             } 
  12.             if (reader.Name == "author"
  13.             { 
  14.                 Response.Write("<b>导演:</b>" + reader.ReadString()); 
  15.                 Response.Write("<br />"); 
  16.             } 
  17.         } 
  18.     } 
  19.     reader.Close(); 

films.xml:

 

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <films> 
  3.     <film> 
  4.         <title>建国大业</title> 
  5.         <author>黄建新</author> 
  6.     </film> 
  7.     <film> 
  8.         <title>山楂树</title> 
  9.         <author>张艺谋</author> 
  10.     </film>     
  11. </films> 

  2.XmlTextWriter写XML文件

 

  1. protected void Page_Load(object sender, EventArgs e) 
  2.     string xmlFile = Server.MapPath("new.xml"); 
  3.     XmlTextWriter writer = new XmlTextWriter(xmlFile, null); 
  4.     writer.WriteStartDocument(true); 
  5.     writer.WriteStartElement("students"); 
  6.     for (int i = 1; i <= 5; i++) 
  7.     { 
  8.         writer.WriteElementString("student""学生" + i.ToString()); 
  9.     } 
  10.     writer.WriteEndElement(); 
  11.     writer.WriteEndDocument(); 
  12.     writer.Close(); 
  13.     Response.Write("文档new.xml生成成功!"); 

new.xml:

  1. <?xml version="1.0" standalone="yes" ?>  
  2. <students> 
  3. <student>学生1</student>  
  4. <student>学生2</student>  
  5. <student>学生3</student>  
  6. <student>学生4</student>  
  7. <student>学生5</student>  
  8. </students>