标签:
class Program { static void Main( string [] args) { var xDoc = new XDocument( new XElement( "root" , new XElement( "dog" , new XText( "dog said black is a beautify color" ), new XAttribute( "color" , "black" )), new XElement( "cat" ), new XElement( "pig" , "pig is great" ))); //xDoc输出xml的encoding是系统默认编码,对于简体中文操作系统是gb2312 //默认是缩进格式化的xml,而无须格式化设置 xDoc.Save(Console.Out); Console.Read(); } } |
<? xml version="1.0" encoding="gb2312"?> < root > < dog color="black">dog said black is a beautify color</ dog > < cat /> < pig >pig is great</ pig > </ root > |
class Program { static void Main( string [] args) { var xDoc = new XDocument( new XElement( "root" , new XElement( "dog" , new XText( "dog said black is a beautify color" ), new XAttribute( "color" , "black" )), new XElement( "cat" ), new XElement( "pig" , "pig is great" ))); //xDoc输出xml的encoding是系统默认编码,对于简体中文操作系统是gb2312 //默认是缩进格式化的xml,而无须格式化设置 xDoc.Save(Console.Out); Console.WriteLine(); var query = from item in xDoc.Element( "root" ).Elements() select new { TypeName = item.Name, Saying = item.Value, Color = item.Attribute( "color" ) == null ?( string ) null :item.Attribute( "color" ).Value }; foreach ( var item in query) { Console.WriteLine( "{0} ‘s color is {1},{0} said {2}" ,item.TypeName,item.Color?? "Unknown" ,item.Saying?? "nothing" ); } Console.Read(); } } |
3. Linq to xml简单的应用
应用需求: 读取博客园的rss,然后在页面上输出最新的10篇博客信息
实现要点: 通过XDocument的Load静态方法载入Xml,通过linq查询最新10条数据
代码如下:
<%@ Page Language="C#" AutoEventWireup="true" %> < script runat="server"> protected override void OnLoad(EventArgs e) { //实际应用,通过读取博客园的RSS生成Html代码显示最新的博客列表 //使用XDocument的Load静态方法载入Xml //玉开技术博客 http://www.cnblogs.com/yukaizhao var rssXDoc = XDocument.Load("http://www.cnblogs.com/rss"); //使用linq to xml查询前10条新博客 var queryBlogs = (from blog in rssXDoc.Descendants("item") select new { Title = blog.Element("title").Value, Url = blog.Element("link").Value, PostTime = DateTime.Parse(blog.Element("pubDate").Value) }).Take(20); repeaterBlogs.DataSource = queryBlogs; repeaterBlogs.DataBind(); base.OnLoad(e); } </ script > <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> < head runat="server"> < title >Linq to Xml 实例</ title > </ head > < body > < ol > < asp:Repeater ID="repeaterBlogs" EnableViewState="false" runat="server"> < ItemTemplate > < li >< span style="float: right"> <%#Eval("PostTime") %></ span >< a href="<%#Eval("Url") %>"><%#Eval("Title") %></ a ></ li > </ ItemTemplate > </ asp:Repeater > </ ol > </ body > </ html > |
C#处理Xml的相关随笔:
标签:
原文地址:http://www.cnblogs.com/itjeff/p/4262595.html