欢迎访问我的个人博客:三秋邦

使用XDocument类创建和读取XML文件

前台:<asp:Label ID="lblXml" runat="server" Text=""></asp:Label>

后台:

View Code
 1 //请添加以下两个命名空间
2 using System.Xml.Linq;
3 using System.Text;
4
5 public partial class _Default : System.Web.UI.Page
6 {
7 protected void Page_Load(object sender, EventArgs e)
8 {
9 WriteXML();
10 ReadXML();
11 }
12
13 private void WriteXML() //创建一个XML文件
14 {
15 XDocument doc = new XDocument(
16 new XDeclaration("1.0", "utf-8", "yes"),//创建版本<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
17 new XComment("Created:" + DateTime.Now.ToString()),//创建注释节点
18 new XElement("DvdList", //创建元素
19 new XElement("DVD",
20 new XAttribute("ID", "1"), //创建属性(特性)
21
22 new XAttribute("Category", "Secience Fiction"),
23 new XElement("Title", "The Matrix"),
24 new XElement("Director", "Larry Wachowski"),
25 new XElement("Price", "12.2"),
26 new XComment("dfdfdddddddddddddddddddddddddddddddd"),
27 new XElement("starring",
28 new XElement("star", "Keanu Reeves"),
29 new XElement("star", "Laurence fishburne")
30 )
31 ),
32 new XElement("DVD",
33 new XAttribute("ID", "2"),
34 new XAttribute("Category", "Drama"),
35 new XElement("Title", "Forrest Gump"),
36 new XElement("Director", "Robert zemeckis"),
37 new XElement("Price", "23.3"),
38 new XElement("Starring",
39 new XElement("star", "sb"),
40 new XElement("star", "aaa")
41 )
42 )
43 )
44 );
45 doc.Save(Server.MapPath("DvdList.xml")); //保存为DvdList.xml
46 }
47 private void ReadXML() //读取上面创建的XML文件DvdList.xml
48 {
49 string xmlFile = Server.MapPath("DvdList.xml"); //获取XML文件的路径
50 XDocument doc = XDocument.Load(xmlFile); //读取计算机内在中
51
52 StringBuilder sb = new StringBuilder();
53 foreach (XElement element in doc.Element("DvdList").Elements())
54 {
55 sb.Append("<ul><b>");
56 sb.Append((string)element.Element("Title"));
57 sb.Append("</b><li>");
58 sb.Append((string)element.Element("Director"));
59 sb.Append("</li><li>");
60 sb.Append(String.Format("{0:c}", (Decimal)element.Element("Price")));
61 sb.Append("</li></ul>");
62 }
63 lblXml.Text = sb.ToString();
64 }
65 }

 

posted @ 2012-01-17 20:35  追夢  阅读(4161)  评论(3编辑  收藏  举报
欢迎访问我的个人博客:三秋邦