LINQ to XML提供了更方便的读写xml方式。前几篇文章的评论中总有朋友提,你为啥不用linq to xml?现在到时候了,linq to xml出场了。

.Net中的System.Xml.Linq命名空间提供了linq to xml的支持。这个命名空间中的XDocument,XElement以及XText,XAttribute提供了读写xml文档的关键方法。

1. 使用linq to xml写xml:

使用XDocument的构造函数可以构造一个Xml文档对象;使用XElement对象可以构造一个xml节点元素,使用XAttribute构造函数可以构造元素的属性;使用XText构造函数可以构造节点内的文本。

如下实例代码:

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:

<?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>


可以看出linq to xml比XmlDocument和XmlWriter要方便很多。



2. 使用linq to xml 读取xml

Linq是从集合中查询对象,在linq to xml中的集合是通过XElement的Elements(),Elements(string name),以及Descendants、DescendantsAndSelf、Ancestors、AncestorsAndSelf的几个重载方法中获得。

获得XElement集合之后,可以通过XElement的Attribute(string name)方法获得元素的属性值,可以通过XElement的Value属性获得节点的文本值;使用linq就可以方便的做查询,做筛选排序了

还是上例中的xml,我们要读取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.php.cn/        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"><html xmlns="http://www.w3.org/1999/xhtml"><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越来越简单了。

C#处理Xml的相关随笔:

1.通过XmlDocument读写Xml文档

2.使用XmlReader读Xml,使用XmlWriter写Xml

3.使用Linq to xml存取XML

4.通过XmlScheme定义固定格式xml文档

5.Xml序列化或者反序列化类

6.通过XPath查找Xml节点

7.通过Xslt转化Xml格式


更多linq to xml操作XML的方法相关文章请关注PHP中文网!

更多相关文章

  1. 详细介绍XML中的属性学习方法
  2. XML中的代码注释书写方法的详解
  3. 分享.net 操作xml的简单方法及说明
  4. 用javascript操作xml方法与技巧的示例代码详解
  5. php解析xml方法实例(附代码)详细说明
  6. 数据中有'<'、'&'符号时,封装的XML就无法解析的解决方法
  7. 详细介绍Mybatis在Xml中处理大于号和小于号的方法
  8. 简单介绍百度新闻开放协议XML文档制作方法
  9. 详细介绍xml的使用方法总结

随机推荐

  1. Python排序傻傻分不清?一文看透sorted与so
  2. 用Python实现跳一跳自动跳跃。
  3. 2018年原创精选文章汇总
  4. OpenCV:目标跟踪。
  5. 自然语言处理中句子相似度计算的几种方法
  6. 4、输入、输出重定向、管道符、Vim编辑器
  7. 一言不合就改成 777 权限?会出人命的!
  8. 干货 | SQL如何学?分享5大免费学习资源
  9. 如何不再当分母?我告诉你一个方法
  10. 最新深度学习合集:GitHub趋势排行第一位,仅