C # LINQ to XML

Source: Internet
Author: User

Looking for someone else's article, address http://www.cnblogs.com/mingmingruyuedlut/archive/2011/01/27/1946239.html

  LINQ to XML provides an efficient way to create XML elements, called function constructs. A function construct is the ability to create an XML tree in a single statement.

The LINQ to XML programming interface that enables function construction has several important features:

  The XElement constructor can take more than one type of parameter to the content. For example, you can pass another XElement object, which becomes a child element. you can pass an XAttribute object that becomes a property of the element. You can also pass any other type of object that is converted to a string and becomes the text content of the element.

  The XElement function takes a params array of type Object , so you can pass any number of objects to the constructor. This allows you to create elements with complex content. if the object is actually

Now Ienumerable<t>, enumerates the collections in the object and adds all the items in the collection.

If the collection contains XElement or XAttribute objects, each item in the collection is added separately. This feature is important because it allows you to pass the results of a LINQ query to the constructor.

The main modules of this paper are:

①: Generating an XML file

②: Traversing the node information of an XML file

③: Modifying node information for an XML file

④: Adding node information to an XML file

⑤: Deleting node information for the specified XML file

①: " generate XML File "
<? XML version= "1.0" encoding= "Utf-8" ?> -<Users> -<User ID= " 111111"> <name>ericsun</name> <password>123456</password> <description>Hello I ' m from Dalian</description> </User> -<User ID= " 222222"> <name>Ray</name> <password>654321</password> <description>Hello I ' m from Jilin</Description> </User> </Users>
With my previous article can be very easy to implement, but I would like to use LINQ to XML implementation of this XML file generation, see the following code: 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Xml.Linq;
6
7 namespace Operatexmllinq
8 {
9 Class Program
10 {
One static void Main (string[] args)
12 {
//xml File Storage Path
String Myxmlpath = "E:\\myusers.xml";
15//Create XML file
Generatexmlfile (Myxmlpath);
17}
18
private static void Generatexmlfile (String xmlpath)
20 {
Try
22 {
23//Define a XDocument structure
XDocument Myxdoc = new XDocument (
New XElement ("Users",
New XElement ("User", New XAttribute ("ID", "111111"),
New XElement ("name", "Ericsun"),
XElement New ("Password", "123456"),
New XElement ("description", "Hello I ' m from Dalian")
30),
New XElement ("User", New XAttribute ("ID", "222222"),
New XElement ("name", "Ray"),
New XElement ("Password", "654321"),
New XElement ("description", "Hello I ' m from Jilin")
35)
36)
37);
38//Save this structure (i.e., the XML file we expect)
Myxdoc.save (Xmlpath);
40}
Exception-catch (ex)
42 {
Console.WriteLine (ex. ToString ());
44}
45}
46}Note: Because of the way LINQ to Xml is used, to introduce namespace System.Xml.Linq ", by running the code above, we can create the structure of the Xml file we envisioned, and we can see that in LINQ this way, It is clear in the code that we know the structure of the XML file we created (as shown in the parameters of the constructor)
②: " traversing node information for XML files " 1 private static void Getxmlnodeinforold (String xmlpath)
2 {
3 Try
4 {
5 XDocument Myxdoc = Xdocument.load (Xmlpath);
6 XElement RootNode = myxdoc.element ("Users");
7 foreach (XElement node in rootnode.elements ("User"))
8 {
9 Console.WriteLine ("User ID = {0}", node. Attribute ("ID"). Value);
10
One string name = node. Element ("name"). Value;
String Password = node. Element ("password"). Value;
String description = node. Element ("description"). Value;
Console.WriteLine ("name = {0} \npassword = {1} \ndescription = {2}", name, password, description);
15}
16}
+ catch (Exception ex)
18 {
Console.WriteLine (ex. ToString ());
20}
21}
22
Getxmlnodeinformation private static void (string Xmlpath)
24 {
Try
26 {
27//define and load nodes from an XML file (root node)
XElement RootNode = Xelement.load (Xmlpath);
29//Query statement: Gets the root node under the name child node (at this point the child node can cross the hierarchy: Grandchild node, great-grandchild node ... )
Ienumerable<xelement> targetnodes = from Target in rootnode.descendants ("name")
Select target;
foreach (XElement node in targetnodes)
33 {
Console.WriteLine ("name = {0}", node. Value);
35}
36
37//Query statement: Gets the id attribute value equals "111111" and all the user nodes of the function child node (side-by-side condition with "&&" symbol connection)
Ienumerable<xelement> mytargetnodes = from Mytarget in rootnode.descendants ("User")
The Mytarget.attribute ("ID"). Value.equals ("111111")
&& mytarget.haselements
Mytarget Select;
(XElement node in mytargetnodes)
42 {
Console.WriteLine ("name = {0}", node. Element ("name"). Value);
Console.WriteLine ("Password = {0}", node. Element ("password"). Value);
Console.WriteLine ("description = {0}", node. Element ("description"). Value);
46}
47}
(Exception ex)
49 {
Console.WriteLine (ex. ToString ());
51}
52}

The above uses two methods to achieve the XML file node information read, the first method is the older pattern: through the parent node to obtain its child nodes (one layer to obtain), and then obtain the information of the target node; the second method uses the LINQ to XML query pattern. All nodes that meet the criteria are obtained according to our requirements, and then the information of those nodes is read.

Next we will briefly talk about the LINQ to XML query pattern (syntax is not too much explained here), one of themost important performance advantages of LINQ to XML (compared to XmlDocument) is: The query in LINQ to XML is statically compiled, and X The Path query must be interpreted at run time, which is a built-in feature of LINQ to XML.

  When we debug the program we find that the second method ienumerable<xelement> Targetnodes = from Target in rootnode.descendants ("name") Select target After this sentence is executed, the resulting targetnodes remains null until the object information is obtained at the time of the Traverse, which is deferred execution, " deferred execution": it means that the expression's calculation is delayed until it really needs its implementation value. deferred execution can greatly improve performance when you have to manipulate large data collections, especially in programs that contain a series of linked queries or operations. in the best case, deferred execution allows only a single circular access to the source collection.

Note: The query condition is written in the where statement, and the condition is concatenated with the "&&" symbol, or the condition is "| |" Symbolic Connection "

③: " modifying node information for XML files " 1 private static void Modifyxmlnodeinforold (String xmlpath)
2 {
3 Try
4 {
5 XDocument Myxdoc = Xdocument.load (Xmlpath);
6 myxdoc.element ("Users"). Element ("User"). Attribute ("ID"). Value = "777777";
7 foreach (XElement node in myxdoc.element ("Users"). Elements ("User"). Elements ("description"))
8 {
9 node. SetValue ("Hello, I ' m from the China.");
10}
Myxdoc.save (Xmlpath);
12}
catch (Exception ex)
14 {
Console.WriteLine (ex. ToString ());
16}
17}
18
private static void Modifyxmlnodeinformation (String xmlpath)
20 {
Try
22 {
23//define and load nodes from an XML file (root node)
XElement RootNode = Xelement.load (Xmlpath);
25//Query statement: Gets all user nodes with an id attribute value equal to "222222" or Equal to "777777" (or conditional "| |") Symbolic Connection)
Ienumerable<xelement> targetnodes = from Target in rootnode.descendants ("User")
The where target. Attribute ("ID"). Value = = "222222"
|| Target. Attribute ("ID"). Value.equals ("777777")
-Select target;
29//Traversal of the obtained target node (collection)
-foreach (XElement node in targetnodes)
31 {
32//Set the innertext of the description node to "Hello, I ' m from USA."
node. Element ("description"). SetValue ("Hello, I ' m from USA.");
34}
35//Save change operation to XML
Rootnode.save (Xmlpath);
37}
Exception-catch (ex)
39 {
Console.WriteLine (ex. ToString ());
41}
42}

  Here also used two methods to obtain the corresponding node information, the specific process please look at the code can be.

④: " adding node information to an XML file " 1 private static void Addxmlnodeinformation (String xmlpath)
2 {
3 Try
4 {
5//define and load nodes from an XML file (root node)
6 XElement RootNode = Xelement.load (Xmlpath);
7//Define a new node
8 XElement NewNode = new XElement ("User", New XAttribute ("ID", "999999"),
9 New XElement ("name", "Rose"),
Ten new XElement ("Password", "456123"),
Each new XElement ("description", "Hello, I ' m from UK"));
12//Add this new node to the root node
Rootnode.add (NewNode);
14//Save change operation to XML
Rootnode.save (Xmlpath);
16}
+ catch (Exception ex)
18 {
Console.WriteLine (ex. ToString ());
20}
21}

Simply make a summary: The following method adds the child content to XElement or XDocument:

Method description

Add content at the end of XContainer's child content.

AddFirst add content at the beginning of XContainer's child content.

The following method adds the content as a sibling of the xnode. The most common node to which you add sibling content is XElement, but you can also add valid sibling content to other types of nodes.

such as XText or xcomment.

Method description

Addafterself add content after xnode.

Addbeforeself add content in front of XNode.

⑤: " Delete node information for the specified XML file " How do you delete the node you just joined? Take a look at the following code:

1 private static void Deletexmlnodeinformation (String xmlpath)
2 {
3 Try
4 {
5//define and load nodes from an XML file (root node)
6 XElement RootNode = Xelement.load (Xmlpath);
7//Query statement: Gets all user nodes with an id attribute value equal to "999999"
8 ienumerable<xelement> targetnodes = from Target in rootnode.descendants ("User")
9 where target. Attribute ("ID"). Value.equals ("999999")
Ten select target;
11
12//removes each node in the resulting node collection from its corresponding parent node in turn
Targetnodes.remove ();
14//Save change operation to XML
Rootnode.save (Xmlpath);
16}
+ catch (Exception ex)
18 {
Console.WriteLine (ex. ToString ());
20}
21}At this point, we will complete the basic operation of the XML file: Create, read, modify, add, delete. As a result of just learning LINQ, understanding is very simple, if there are inappropriate places, you are welcome to point out ~ ~

C # LINQ to 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.