LINQ to XML provides a more convenient way to read and write XML. The comments in the previous articles have always been mentioned by friends, why don't you use LINQ to XML? Now it's time to get the LINQ to XML out. The System.Xml.Linq namespace in net provides support for LINQ to XML. The Xdocument,xelement and Xtext,xattribute in this namespace provide a key way to read and write XML documents.
1. Write XML using LINQ to XML:Using the XDocument constructor, you can construct an XML document object, use a XElement object to construct an XML node element, use the XAttribute constructor to construct the attributes of the element, and use the Xtext constructor 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输出xml的encoding是系统默认编码,对于简体中文操作系统是gb2312
//默认是缩进格式化的xml,而无须格式化设置
xDoc.Save(Console.Out);
Console.Read();
}
}
|
The above code will output the following 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
>
|
You can see that LINQ to XML is much more convenient than XmlDocument and XmlWriter.
2. Reading XML using LINQ to XMLLINQ is the query object from the collection, the collection in LINQ to XML is through XElement's Elements (), Elements (string name), and descendants, Descendantsandself, Ancestors and Ancestorsandself are obtained in several overloaded methods. After obtaining the XElement collection, you can get the attribute value of the element through the XElement attribute (string name) method, you can get the text value of the node through the Value property of the XElement, and it is convenient to do the query using LINQ Do the filtering sort or the XML in the example above, we want to read all the byte points of root and print out the following 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输出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. Simple application of LINQ to XML
Application requirements: Read the RSS of the blog park and then output the latest 10 blog posts on the page
Implementation key: Loading XML through XDocument's load static method, querying the latest 10 data through LINQ
The code is as follows:
?
<%@ Page Language="C#" AutoEventWireup="true" %>
<
script runat="server">
protected override void OnLoad(EventArgs e)
{
//实际应用,通过读取博客园的RSS生成Html代码显示最新的博客列表
//使用XDocument的Load静态方法载入Xml
//玉开技术博客 http://www.cnblogs.com/yukaizhao
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
>
|
The development of C # makes it easier to read and write XML.
C # Related essays on XML processing:
1. Read and write XML documents via XmlDocument 2. Use XmlReader to read XML and write XML3 using XmlWriter. Using LINQ to XML Access XML4. Defines a fixed-format XML document 5.XML serialization or deserialization by Xmlscheme 6. Finding XML nodes through XPath 7. Transforming XML Formats through XSLT
C # operations Xml:linq to XML operation XML