Analysis of the xml parsing by using linq to XML

Source: Internet
Author: User

The System. Xml. Linq namespace in. Net provides the support for linq to xml. XDocument, XElement, and XText and XAttribute in this namespace provide key methods for reading and writing xml documents.
1. Use linq to xml to write xml:
The XDocument constructor can be used to construct an Xml document object. The XElement object can be used to construct an xml node element. The XAttribute constructor can be used to construct element attributes; the XText constructor can be used to construct the text in the node.
Example code:
Copy codeThe Code is 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 ")));

// The encoding of xml output by xDoc is the system default encoding, and gb2312 is used for the simplified Chinese operating system.
// By default, the xml format is indented without formatting.
XDoc. Save (Console. Out );

Console. Read ();
}
}

The above code will output the following Xml:
Copy codeThe Code is 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 the convenience of linq to xml is much higher than that of XmlDocument and XmlWriter.
2. Use linq to xml to read xml
The object is queried from the collection, and the collection in the Linq to xml is queried through the Elements (), Elements (string name ), and several overload methods of Descendants, DescendantsAndSelf, Ancestors, and AncestorsAndSelf.
After the XElement set is obtained, 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 perform queries and sort by filtering.
Or the xml in the above example. We need to read all the bytes of the root and print them out, as shown in the following code:
Copy codeThe Code is 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 ")));

// The encoding of xml output by xDoc is the system default encoding, and gb2312 is used for the simplified Chinese operating system.
// By default, the xml format is indented without formatting.
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 Applications of Linq to xml
Application requirement: Read the rss of the blog site and output the latest 10 blog posts on the page.
Implementation key points: Load Xml using the XDocument Load Static Method, and query the latest 10 data records through linq
The Code is as follows:
Copy codeThe Code is as follows:
<% @ Page Language = "C #" AutoEventWireup = "true" %>
<Script runat = "server">
Protected override void OnLoad (EventArgs e)
{
// In practical application, the Html code generated by reading the RSS of the blog park shows the latest blog list
// Load Xml using the Load Static Method of XDocument
Var rssXDoc = XDocument. Load ("http://www.jb51.net ");

// Use linq to xml to query the first 10 new blogs
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 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>

C # makes reading and writing Xml easier.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.