Analysis of an example of linq to xml operating XML

  • 2020-06-07 04:21:21
  • OfStack

The System. Xml. Linq namespace in.Net provides support for linq to xml. XDocument, XElement, and XText, XAttribute in this namespace provide key methods for reading and writing xml documents.
1. linq to xml xml
1 Xml document object can be constructed using the XDocument constructor. One xml node element can be constructed using the XElement object, and the attributes of the element can be constructed using the XAttribute constructor. The XText constructor is used to construct the text within the node.
The following example code:

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 The output xml the encoding Is the default code for the simplified Chinese operating system gb2312
        // The default is indented formatting xml Without formatting Settings 
        xDoc.Save(Console.Out);

        Console.Read();
    }
}

The above code outputs Xml as follows:

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

It can be seen that linq to xml is much more convenient than XmlDocument and XmlWriter.
2. Read xml using linq to xml
Linq queries objects from collections, the collections in linq to xml are obtained through Elements(),Elements(string name), and several overloaded methods of Descendants, DescendantsAndSelf, Ancestors, AncestorsAndSelf.
After obtaining the XElement set, the attribute value of the element can be obtained through the Attribute(string name) method of XElement, and the text value of the node can be obtained through the Value attribute of XElement. Using linq, you can easily do the query, do the filter sort
Again, xml in the example above, we want to read all the byte points of root and print them out, as follows:

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 The output xml the encoding Is the default code for the simplified Chinese operating system gb2312
        // The default is indented formatting xml Without formatting Settings 
        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. Simple application of Linq to xml
Application requirements: Read rss in the blogosphere and output the latest 10 blog posts on the page
Implementation points: Load Xml via Load static method and query the latest 10 data via linq
The code is as follows:

<%@ Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
    protected override void OnLoad(EventArgs e)
    {
        // The practical application , By reading blogosphere RSS generate Html The code shows the latest list of blogs 
        // use XDocument the Load Static method loading Xml
        var rssXDoc = XDocument.Load("https://www.ofstack.com");

        // use linq to xml Before the query 10 A new blog 
        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  The instance </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>

The development of C# has made it easier to read and write Xml.

Related articles: