当前位置: 移动技术网 > IT编程>开发语言>.net > 解析linq to xml操作XML的示例分析

解析linq to xml操作XML的示例分析

2017年12月12日  | 移动技术网IT编程  | 我要评论

屠神修仙,美女走过光吹裙子,乱陈俊

.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
        var rssxdoc = xdocument.load("//www.jb51.net");

        //使用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越来越简单了。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网