1.XmlTextReader读XML文件
- protected void Page_Load(object sender, EventArgs e)
- {
- string xmlFile = Server.MapPath("films.xml");
- XmlTextReader reader = new XmlTextReader(xmlFile);
- while (reader.Read())
- {
- if (reader.NodeType == XmlNodeType.Element)
- {
- if (reader.Name == "title")
- {
- Response.Write("<b>名称:</b>" + reader.ReadString());
- }
- if (reader.Name == "author")
- {
- Response.Write("<b>导演:</b>" + reader.ReadString());
- Response.Write("<br />");
- }
- }
- }
- reader.Close();
- }
films.xml:
- <?xml version="1.0" encoding="utf-8" ?>
- <films>
- <film>
- <title>建国大业</title>
- <author>黄建新</author>
- </film>
- <film>
- <title>山楂树</title>
- <author>张艺谋</author>
- </film>
- </films>
2.XmlTextWriter写XML文件
- protected void Page_Load(object sender, EventArgs e)
- {
- string xmlFile = Server.MapPath("new.xml");
- XmlTextWriter writer = new XmlTextWriter(xmlFile, null);
- writer.WriteStartDocument(true);
- writer.WriteStartElement("students");
- for (int i = 1; i <= 5; i++)
- {
- writer.WriteElementString("student", "学生" + i.ToString());
- }
- writer.WriteEndElement();
- writer.WriteEndDocument();
- writer.Close();
- Response.Write("文档new.xml生成成功!");
- }
new.xml:
- <?xml version="1.0" standalone="yes" ?>
- <students>
- <student>学生1</student>
- <student>学生2</student>
- <student>学生3</student>
- <student>学生4</student>
- <student>学生5</student>
- </students>