// 创建一个XmlDocument对象,用于载入存储信息的XML文件
XmlDocument xdoc = new XmlDocument();
xdoc.Load(Server.MapPath("guestbook.xml"));
// 创建一个新的guest节点并将它添加到根节点下
XmlElement parentNode = xdoc.CreateElement("guest");
xdoc.DocumentElement.PrependChild(parentNode);
// 创建所有用于存储信息的节点
XmlElement namenode = xdoc.CreateElement("name");
XmlElement emailNode = xdoc.CreateElement("email");
XmlElement qqNode = xdoc.CreateElement("qq");
XmlElement homepageNode = xdoc.CreateElement("homepage");
XmlElement commentNode = xdoc.CreateElement("comment");
// 获取文本信息
XmlText nameText = xdoc.CreateTextNode(TextBox1.Text);
XmlText emailText = xdoc.CreateTextNode(TextBox2.Text);
XmlText qqText = xdoc.CreateTextNode(TextBox3.Text);
XmlText homepageText = xdoc.CreateTextNode(TextBox4.Text);
XmlText commentText = xdoc.CreateTextNode(TextBox5.Text);
// 将上面创建的各个存储信息的节点添加到guest节点下但并不包含最终的值
parentNode.AppendChild(namenode);
parentNode.AppendChild(emailNode);
parentNode.AppendChild(qqNode);
parentNode.AppendChild(homepageNode);
parentNode.AppendChild(commentNode);
// 将上面获取的文本信息添加到与之相对应的节点中
namenode.AppendChild(nameText);
emailNode.AppendChild(emailText);
qqNode.AppendChild(qqText);
homepageNode.AppendChild(homepageText);
commentNode.AppendChild(commentText);
xdoc.Save(Server.MapPath("guestbook.xml"));
xslt转换
Xml1.DocumentSource = Server.MapPath("guestbook.xml");
Xml1.TransformSource = Server.MapPath("guestBook.xslt");
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("guestbook.xml"));
this.GridView1.DataSource = ds.Tables[0].DefaultView;
this.GridView1.DataBind();
下载文件 guestbookxml 和xslt文件格式
2. linq
XDocument xdoc = XDocument.Load(Server.MapPath("guestbook.xml"));//var
var zz = from p in xdoc.Elements("guestbook").Elements("guest")
where (p.Attribute("style")== null)||(p.Attribute("style").Value!="display")
select new { name = p.Element("name").Value, emali = p.Element("email").Value, qq = p.Element("qq").Value };
GridView1.DataSource = zz;
GridView1.DataBind();
创建
XDocument xdoc = new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement("guestbook",
new XElement("guest",
new XElement("name", "jack"),
new XElement("age", "20")),
new XElement("guest",
new XElement("name", "tom"),
new XElement("age", "15"))
));
xdoc.Save(Server.MapPath("aa.xml"));
查找
var aa = from a in xdoc.Descendants("name")
where a.Value == "jack"
select a;
foreach (var aaa in aa)
{
Response.Write(aaa);
}