|
在.net 3.5版本之前,生成XML文档是比较麻烦的,必须先建立Xmldoucument文件,然后用AppendChildNode等方法来操作,费时费力。运用最新的LINQ TO XML技术,不费吹灰之力即可生成XML,过程简单到你都不再相信自己的眼睛吧。下面就是一段演示动态生成网站的sitemap文件,为本网站心云图片中的一段代码:- protected void btnUpload1_Click(object sender, EventArgs e)//生成站点地图
- {
- string xmlFile=MapPath("~/App_Data/ImageCategory.xml");
- string newXmlFile=MapPath("~/App_Data/ImageCategory.sitemap");
- XDocument doc=XDocument.Load(xmlFile);
- string connectionString = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=") + MapPath("~/App_Data/Image.mdb");
- string sqltext = @"SELECT * FROM [Image] ";
- OleDbDataAdapter ImageAdapter = new OleDbDataAdapter(sqltext, connectionString);
- DataSet ImageDS=new DataSet();
- ImageAdapter.Fill(ImageDS, "Image");
- ArrayList categorys=new ArrayList();
- foreach(XElement element in doc.Element("Categorys").Elements())
- {
- if ((string)element.Attribute("Text") == "首页")
- continue;
- string category =(string)element.Attribute("Text");
- DataRow[] ImageRows=ImageDS.Tables["Image"].Select("CategoryName='"+category+"'");
- ArrayList images=new ArrayList();
- foreach(DataRow ImageRow in ImageRows)
- images.Add(new XElement("siteMapNode",new XAttribute("url","GetImage.aspx?Photo="+ImageRow["ImageID"].ToString()),
- new XAttribute("title",ImageRow["Title"].ToString())));
- categorys.Add(new XElement("siteMapNode",new XAttribute("url","ShowImage.aspx?CategoryName="+(string)element.Attribute ("Text")),
- new XAttribute("title",(string)element.Attribute("Text")), images.ToArray(typeof(XElement))));
- }
- XElement rootelement = new XElement("siteMapNode",new XAttribute("url","Default.aspx"), new XAttribute("title","首页"),categorys.ToArray(typeof(XElement)));
- XDocument newDoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement("{[url]http://schemas.microsoft.com/AspNet/SiteMap-File-1.0[/url]}siteMap",rootelement));
- newDoc.Save(newXmlFile);
- ASPxLabel5.Text = "已成功生成图片站点地图";
- }
复制代码 |
|