Example analysis of parsing LINQ to XML operations XML _ Practical Tips

Source: Internet
Author: User
. NET provides LINQ to XML support for the System.Xml.Linq namespace. The Xdocument,xelement and Xtext,xattribute in this namespace provide a critical way to read and write XML documents.
1. Write XML using LINQ to XML:
You can construct an XML Document object using the XDocument constructor, you can construct an XML node element using the XElement object, you can construct an element's properties using the XAttribute constructor, and you can construct the text within the node using the Xtext constructor.
The following instance code:
Copy Code code as follows:

Class Program
{
static void Main (string[] args)
{
var xdoc = new XDocument (New XElement ("root")
New XElement ("Dog",
New XText ("Dog said is a beautify color"),
New XAttribute ("Color", "black"),
New XElement ("Cat"),
New XElement ("Pig", "Pig is great"));

Xdoc output XML encoding is the system default encoding, for the Simplified Chinese operating system is gb2312
The default is to indent the formatted XML without having to format the settings
Xdoc.save (Console.Out);

Console.read ();
}
}

The code above will output the following XML:
Copy Code code as follows:

<?xml version= "1.0" encoding= "gb2312"?>
<root>
<dog color= "Black" >dog said a beautify color</dog>
<cat/>
<pig>pig is great</pig>
</root>

You can see that LINQ to XML is much more convenient than XmlDocument and XmlWriter.
2. Reading XML using LINQ to XML
LINQ is the query object from the collection, the collection in LINQ to XML is through the XElement Elements (), Elements (string name), and descendants, Descendantsandself, Ancestors, ancestorsandself, are obtained in several overloaded methods.
After you get the XElement collection, you can get the attribute value of the element by using the attribute (string name) method of the XElement, you can get the text value of the node through the XElement Value property, and you can easily do the query by using LINQ. Do the filtering sort.
Or the XML in the example above, we're going to read all the byte points of root and print out the following code:
Copy Code code as follows:

Class Program
{
static void Main (string[] args)
{

var xdoc = new XDocument (New XElement ("root")
New XElement ("Dog",
New XText ("Dog said is a beautify color"),
New XAttribute ("Color", "black"),
New XElement ("Cat"),
New XElement ("Pig", "Pig is great"));

Xdoc output XML encoding is the system default encoding, for the Simplified Chinese operating system is gb2312
The default is to indent the formatted XML without having to format the 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. LINQ to XML Simple application
Application Requirements: Read the RSS in the blog park, and then output the latest 10 blog information on the page
Implementation essentials: Loading XML through the XDocument load static method, querying the latest 10 data through LINQ
The code is as follows:
Copy Code code as follows:

<%@ Page language= "C #" autoeventwireup= "true"%>
<script runat= "Server" >
protected override void OnLoad (EventArgs e)
{
Practical applications, by reading the blog RSS generated HTML code to display the latest blog list
Loading XML using the XDocument load static method
var rssxdoc = xdocument.load ("http://www.jb51.net");

Query the top 10 new blogs with LINQ to XML
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 ">
<title>linq to Xml instance </title>
<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>

The development of C # makes it easier to read and write XML.

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.