using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
namespace XML1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//使用XlmReader讀books.xml中有幾本書
XmlReaderSettings settings=new XmlReaderSettings();
settings.IgnoreComments=true;
settings.IgnoreWhitespace=true;
int booknum = 0;
using (XmlReader reader = XmlReader.Create(Server.MapPath("books.xml"), settings))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.LocalName == "book")
{
booknum++;
}
}
}
}
Response.Write("一共找到了" + booknum + "本書!");
}
//使用XlmWriter寫NewBooks.xml文件。
protected void Button1_Click(object sender, EventArgs e)
{
XmlWriterSettings settings=new XmlWriterSettings();
settings.Encoding=System.Text.Encoding.UTF8;//輸入的編碼
settings.Indent=true;
using (XmlWriter write = XmlWriter.Create(Server.MapPath("newbook.xml"), settings))
{
write.WriteStartDocument();//開始寫
write.WriteStartElement("books");
write.WriteStartElement("book");//book節點開始
write.WriteStartAttribute("id");//給book添加屬性
write.WriteValue("1");//設置屬性id的值爲1
write.WriteEndAttribute();//結束屬性
write.WriteStartElement("author");//author節點
write.WriteString("張聞正");//author節點中的內容
write.WriteEndElement();//結束author節點
write.WriteEndElement();//結束book節點
//再添一本書
write.WriteStartElement("book");//book開始
write.WriteStartElement("author");//author節點
write.WriteString("清華大學出版社");//author節點中的內容
write.WriteEndElement();//結束author節點
write.WriteEndElement();//結束book節點
write.WriteEndElement();
}
this.Response.Write("ok");
}
}
}
使用XlmWrite把一個xml文件寫入輸出流中。在(demo2.aspx運行時顯示xml文檔)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
namespace XML1
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = System.Text.Encoding.UTF8;//輸入的編碼
settings.Indent = true;
using (XmlWriter write = XmlWriter.Create(this.Response.Output, settings))
{
write.WriteStartDocument();//開始寫
write.WriteStartElement("books");
write.WriteStartElement("book");//book節點開始
write.WriteStartAttribute("id");//給book添加屬性
write.WriteValue("1");//設置屬性id的值爲1
write.WriteEndAttribute();//結束屬性
write.WriteStartElement("author");//author節點
write.WriteString("張聞正");//author節點中的內容
write.WriteEndElement();//結束author節點
write.WriteEndElement();//結束book節點
//再添一本書
write.WriteStartElement("book");//book開始
write.WriteStartElement("author");//author節點
write.WriteString("清華大學出版社");//author節點中的內容
write.WriteEndElement();//結束author節點
write.WriteEndElement();//結束book節點
write.WriteEndElement();
}
}
}
}