A detailed explanation of LINQ to XML in C #

Source: Internet
Author: User


Objective

I believe that a lot is engaged. NET developed, it would be cumbersome to manipulate Xml before. NET 3.5, but then LINQ to XML appeared, and today's protagonist is LINQ to XML, with little nonsense to go directly to the subject.


First, generate XML

In order to be able to have a certain organization in the structure, I suggest you create a new console project, and create a new Createxml class (the following sections belong to this class).

and write the following properties in it:


The code is as follows:


public static String Path

{

Get

{

String Path = String.Format ("{0}\\test.xml", environment.currentdirectory);

return path;

}

}

This code is well understood, just for the following example we can save the XML to the current program run path.

(The following example does not include the notation in the main method, because only the static method is called in Main.) )


1. Create a simple XML

First, let's practice practiced hand, create a simple XML and save it to a file.

The code is as follows:


The code is as follows:


<summary>

Create a simple XML and save

</summary>

public static void CreateElement ()

{

XDocument Xdoc = new XDocument (

New Xdeclaration ("1.0", "Utf-8", "yes"),

New XElement ("root",

New XElement ("Item", "1"),

New XElement ("Item", "2")

));

Xdoc. Save (Path);

}

Many people who have learned XML can guess the organization of the final XML from the structure, which is one of the advantages of LINQ to XML. This code first creates an XML document and sets the version of the XML to 1.0,

With UTF-8 encoding, the following yes indicates that the XML is independent. The next step is to create each node, starting with the root node, and then adding two item nodes to the root node.

The resulting XML is as follows:


The code is as follows:


<?xml version= "1.0″encoding=" utf-8″standalone= "yes"?>

<root>

<item>1</item>

<item>2</item>

</root>


2. Create a comment

When there are many items in XML, we need to use annotations to differentiate them, and we can add comments to them through LINQ to XML.

For example, the following code:


The code is as follows:


<summary>

Create a comment

</summary>

public static void Createcomment ()

{

XDocument doc = new XDocument (

New Xdeclaration ("1.0", "Utf-8", "yes"),

New Xcomment ("hint"),

New XElement ("Item", "ASD")

);

Doc. Save (Path);

}

Here we have added a comment directly after the version information.

The final result is as follows:


The code is as follows:


<?xml version= "1.0″encoding=" utf-8″standalone= "yes"?>

<!– hint –>

<item>asd</item>


3. Creating XML based on objects

Most of the time we convert types such as arrays into XML so that we can save them into persistent storage media, so we'll simply cite an example of converting an array to XML.

The code looks like this:


The code is as follows:


<summary>

Create XML based on object and save

</summary>

public static void Createelementbyobjects ()

{

var s = enumerable.range (1, 10);

XElement Xele = new XElement (

"Root",

From item in S

Select New XElement ("Item", item.) ToString ())

);

Xele. Save (Path);

}

The first code var s = Enumerable.radge (1,10) is incremented starting from 1, generating an array of 10 items so that we can add them later, with this array,

We use a simple LINQ statement to convert an array to XML and add it to root.

The results after saving are as follows:


The code is as follows:


<?xml version= "1.0″encoding=" utf-8″?>

<Root>

<item>1</item>

<item>2</item>

<item>3</item>

<item>4</item>

<item>5</item>

<item>6</item>

<item>7</item>

<item>8</item>

<item>9</item>

<item>10</item>

</Root>


4. Create a property

Sometimes we don't want to create a new subkey to save the data, but instead use the property to save it. Rightly so, LINQ to XML also supports this feature, which we can implement with simple statements.

The code looks like this:


The code is as follows:


<summary>

Creating properties

</summary>

public static void Creteattribute ()

{

XAttribute xa = new XAttribute ("V2", "2");

XElement Xele = new XElement (

"Root",

New XElement ("Item",

New XAttribute ("V1", "1"),

Xa

));

Xele. Save (Path);

}

We can still see the familiar syntax, where we use the XAttribute to create a property and add it to the XElement.

The final results are as follows:


The code is as follows:


<?xml version= "1.0″encoding=" utf-8″?>

<Root>

<item v1= "1″v2=" 2″/>

</Root>


5. Create a Namespace

For some enterprise-class XML formats, it is very strict. In particular, there may be duplicates in the same XML, but we want to differentiate between them, and we can use namespaces to separate them (similar to namespaces in C #). )。

The following is an example of creating a namespace:


The code is as follows:


<summary>

Create a Namespace

</summary>

public static void Createnamespace ()

{

XElement Xele = new XElement ("{Http://www.xamarin-cn.com}root",

New XElement ("Item", "1"),

New XElement ("{Http://www.baidu.com}item", 2));

Xele. Save (Path);

}

The results are as follows:


The code is as follows:


<?xml version= "1.0″encoding=" utf-8″?>

<root xmlns= "http://www.xamarin-cn.com" >

<item xmlns= "" >1</Item>

<item xmlns= "http://www.baidu.com" >2</Item>

</Root>

From this result we can see that the corresponding attribute has the xmlns attribute, and the value is the namespace we assign to it.


Second, query and modify the XML

Linq to XML is not just simple to create XML, but is very convenient in terms of query, edit, and delete. Here's what we'll cover.

First we create a queryxml class and write the following attributes in it:


The code is as follows:


public static String Path

{

Get

{

String Path = String.Format ("{0}\\test1.xml", environment.currentdirectory);

return path;

}

}

At the same time, create a new Test1.xml file under the path and write the following in it:


The code is as follows:


<?xml version= "1.0″encoding=" utf-8″?>

<Root>

<item v1= "1″v2=" 2″>item1</item>

<item v1= "1″v2=" 2″>item2</item>

</Root>

Now we can start the formal.


1. Reading XML from a file

Since we need to read the corresponding XML file for the XML query, there are other ways to do it later.

The code is as follows:


The code is as follows:


<summary>

Reading XML from a file

</summary>

public static void Queryelementbyfile ()

{

XElement Xele = Xelement.load (Path);

XElement xele1 = Xele. Element ("Item");

Console.Write (Xele1. Value.trim ());

Console.readkey ();

}

We can use the static method of the XElement load to read the XML file under the specified path, where we not only read the XML file, but also get the value of the first item of the XML and output it.

So we can see the following results:


2. Add a new node before and after the specified node

We're just reading XML and simple queries, and we're not just querying and inserting new nodes before and after that node.

The code is as follows:


The code is as follows:


<summary>

Add a new node before and after the specified node

</summary>

public static void Addtoelementafterandbefore ()

{

XElement Xele = Xelement.load (Path);

var item = (from Ele in Xele. Elements ("Item")

where Ele. Value.equals ("Item2")

Select Ele). Singleordefault ();

if (item! = NULL)

{

XElement Nele = new XElement ("Nitem", "Nitem");

XElement nele2 = new XElement ("Bitem", "Bitem");

Item. Addafterself (Nele);

Item. Addbeforeself (Nele2);

Xele. Save (Path);

}

}

We simply analyze the above code, first we use LINQ to query the value of item ITEM2 node, and then get the first node, and then through Addafterself and addbeforeself to add a new node behind and before the node.

The XML results after the addition are as follows:


The code is as follows:


<?xml version= "1.0″encoding=" utf-8″?>

<Root>

<item v1= "1″v2=" 2″>item1</item>

<BItem>BItem</BItem>

<item v1= "1″v2=" 2″>item2</item>

<NItem>NItem</NItem>

</Root>


3. Adding attributes to a node

We have been able to add nodes dynamically, but not only can we create nodes, but we can create properties as well, and setattributevalue to add new properties or modify existing ones.

The code is as follows:


The code is as follows:


<summary>

Adding attributes to a node

</summary>

public static void Addattributetoele ()

{

XElement Xele = Xelement.parse (@ "<?xml version= ' 1.0′encoding= ' utf-8′?><root><!– in front of comments –>

<item v1= ' 1′v2= ' 2′>item1</item><!– behind comments –><item v1= ' 1′v2= ' 2′v3= ' 3′>item2</item>< /root> ");

var item = (from Ele in Xele. Elements ("Item")

where Ele. Value.equals ("Item2")

Select Ele). Singleordefault ();

Item. Setattributevalue ("V3", "3");

Xele. Save (Path);

}

We can clearly see that here we are not using Xelement.load to read the XML file, but rather by reading the XML string directly. Then we go to the same query as above, and then add the new properties through Setattributevalue and save.

The XML content is as follows:


The code is as follows:


<?xml version= "1.0″encoding=" utf-8″?>

<Root>

<!– comments in front of –>

<item v1= "1″v2=" 2″>item1</item>

<!– the comment behind the –>

<item v1= "1″v2=" 2″v3= "3″>item2</item>

</Root>

We can see that the second item has more than one v3= "3" new property.


4. Add comments before and after the specified node

The syntax here is basically similar to the addition of nodes to a specified node, except that the XML is read in different ways.

The code is as follows:


The code is as follows:


<summary>

Add comments to a node before and after

</summary>

public static void Addcommenttoafterandbefore ()

{

TextReader tr = new StringReader (@ "<?xml version= ' 1.0′encoding= ' utf-8′?><root><!– in front of comments –>

<item v1= ' 1′v2= ' 2′>item1</item><!– behind comments –><item v1= ' 1′v2= ' 2′v3= ' 3′>item2</item>< /root> ");

XElement Xele = xelement.load (tr);

var item = (from Ele in Xele. Elements ("Item")

where Ele. Value.equals ("Item1")

Select Ele). FirstOrDefault ();

if (item! = NULL)

{

Xcomment xcom = new Xcomment ("comments later");

Xcomment Xcoma = new Xcomment ("previous comment");

Item. Addafterself (xcom);

Item. Addbeforeself (Xcoma);

}

Tr. Close ();

Xele. Save (Path);

}

Above I use StringReader and TextReader to read the XML string and use Xelement.load to read the object, then the new node is created as a comment node, and finally with the same syntax to add to the specified node before and after.

The final result is as follows:


The code is as follows:


<?xml version= "1.0″encoding=" utf-8″?>

<Root>

<!– comments in front of –>

<!– comments in front of –>

<item v1= "1″v2=" 2″>item1</item>

<!– the comment behind the –>

<!– the comment behind the –>

<item v1= "1″v2=" 2″v3= "3″>item2</item>

</Root>


5. Replace the specified node

Modifying the value of a node can be done by SetValue, but sometimes it involves child nodes, and we want to replace them all at once, then we need to use replacewith.

The code is as follows:


The code is as follows:


<summary>

Replace the specified node

</summary>

public static void Replaceelement ()

{

XElement Xele = Xelement.load (Path);

var item = (from Ele in Xele. Elements ("Item")

where Ele. Value.equals ("Item2")

Select Ele). FirstOrDefault ();

if (item! = NULL)

{

Item. ReplaceWith (New XElement ("Item", "Item3"));

}

Xele. Save (Path);

}

The focus here is on the ReplaceWith method, which takes two actions to invoke the method. The first is to delete the node, and then replace our node insertion complete at the node's location.

The final XML results are as follows:


The code is as follows:


<?xml version= "1.0″encoding=" utf-8″?>

<Root>

<!– comments in front of –>

<!– comments in front of –>

<item v1= "1″v2=" 2″>item1</item>

<!– the comment behind the –>

<!– the comment behind the –>

<Item>Item3</Item>

</Root>

This makes it easy for us to replace the entire node.


6. Delete the specified attribute

We described the creation, modification, and addition of properties, but did not describe how to delete the specified properties, as shown in a simple example.

The code is as follows:


The code is as follows:


<summary>

Delete the specified property

</summary>

public static void RemoveAttribute ()

{

XElement Xele = Xelement.load (Path);

var item = (from Ele in Xele. Elements ("Item")

where Ele. Value.equals ("Item1")

Select Ele). FirstOrDefault (). Attribute ("v1");

if (item! = NULL)

{

Item. Remove ();

}

Xele. Save (Path);

}

We first query the specified node, then specify a property, and finally call the XAttribute remove method.

The results are as follows:


The code is as follows:


<?xml version= "1.0″encoding=" utf-8″?>

<Root>

<!– comments in front of –>

<!– comments in front of –>

<item v2= "2″>item1</item>

<!– the comment behind the –>

<!– the comment behind the –>

<Item>Item3</Item>

</Root>


7. Delete the specified node

Since the properties can be removed from the above, it is natural to delete the attributes.

The code looks like this:


The code is as follows:


<summary>

Delete the specified node

</summary>

public static void Removeelement ()

{

XElement Xele = Xelement.load (Path);

var item = (from Ele in Xele. Elements ("Item")

where Ele. Value.equals ("Item1")

Select Ele). FirstOrDefault ();

if (item! = NULL)

{

Item. Remove ();

}

Xele. Save (Path);

}

The same method is still called.

The results are as follows:


The code is as follows:


<?xml version= "1.0″encoding=" utf-8″?>

<Root>

<!– comments in front of –>

<!– comments in front of –>

<!– the comment behind the –>

<!– the comment behind the –>

<Item>Item3</Item>

</Root>


Third, query by node relationship

The above query is through the relevant conditions to query, but we sometimes just need to pass the relationship between, so that can avoid a lot of code, of course, a little exploration can be found in fact XElement are provided to us.

We still want to create a new Structurexml class and create a new property in it.

As shown below:


The code is as follows:


public static String Path

{

Get

{

String Path = String.Format ("{0}\\test2.xml", environment.currentdirectory);

return path;

}

}

Create a new test2.xml under this folder and write the following:


The code is as follows:


<?xml version= "1.0″encoding=" utf-8″?>

<Root>

<Item>

<SubItem1>

1

</SubItem1>

<SubItem>

<Child>

Sss

</Child>

</SubItem>

<SubItem2>

2

</SubItem2>

</Item>

</Root>


1. Display all parent nodes of the specified node

From the XML file above, we can clearly see that XML is structured and has a relationship with each other, and now we need to display the name of the parent node of a node.

The code looks like this:


The code is as follows:


<summary>

Displays all parent nodes of the specified node

</summary>

public static void Showallparentele ()

{

XElement Xele = Xelement.load (Path);

var item = (from Ele in Xele. Descendants ("Child")

Select Ele). FirstOrDefault ();

if (item! = NULL)

{

foreach (var sub in item.) Ancestors ())

{

Console.WriteLine (Sub. Name);

}

Console.WriteLine ("—————-");

foreach (var sub in item.) Ancestorsandself ())

{

Console.WriteLine (Sub. Name);

}

Console.readkey ();

}

}

Where we get the bottom node through descendants, and then we use ancestors to get all the parent nodes, and Ancestorsandself is the one that contains itself.

The final result is as follows:

We see that the split line shows that it does not contain itself, and the following contains itself.


2. Display all child nodes of the specified node

Not only can we output all the parent nodes of a node, but we can also output all the child nodes of a node.

The code looks like this:


The code is as follows:


<summary>

Displays all child nodes of the specified node

</summary>

public static void Showallchildele ()

{

XElement Xele = Xelement.load (Path);

foreach (var sub in Xele. Descendants ())

{

Console.WriteLine (Sub. Name);

}

Console.WriteLine ("————— –");

foreach (var sub in Xele. Descendantsandself ())

{

Console.WriteLine (Sub. Name);

}

Console.readkey ();

}

Here we are still dividing the output sub-node and containing its own.

The results are as follows:


3. Display the node before the sibling node

Since there is a parent-child relationship, of course, there is also a sibling relationship, first we first show the node before the sibling node.

The code looks like this:


The code is as follows:


<summary>

Node before the sibling node is displayed

</summary>

public static void Showprevele ()

{

XElement Xele = Xelement.load (Path);

var item = (from Ele in Xele. Descendants ("subitem")

Select Ele). FirstOrDefault ();

if (item! = NULL)

{

foreach (var sub in item.) Elementsbeforeself ())

{

Console.WriteLine (Sub. Name);

}

}

Console.readkey ();

}

Here we see that we get the sibling node before the node through Elementsbeforeself, and of course we can pass in the parameter as a restriction condition. Here we get the subitem node through the query and show the sibling nodes before the node.

The final result is as follows:


4. Display the nodes behind the sibling node

As a supplement to the above.

The code looks like this:


The code is as follows:


<summary>

Display nodes following a sibling node

</summary>

public static void Shownextele ()

{

XElement Xele = Xelement.load (Path);

var item = (from Ele in Xele. Descendants ("subitem")

Select Ele). FirstOrDefault ();

if (item! = NULL)

{

foreach (var sub in item.) Elementsafterself ())

{

Console.WriteLine (Sub. Name);

}

}

Console.readkey ();

}

The final result is as follows:


Iv. Listening FOR XML events

You may wonder why the XML is listening, in fact, this is meaningful, such as you want to depend on the value of a node, then you have to listen to this node, if this node changes,

You can respond in a timely manner. But the XML event listener has a feature similar to the DOM event in the browser, listening to the event that the parent node can also listen to its child nodes. Below we

This is illustrated by a simple example.

The instance code is as follows:


The code is as follows:


public static Class Eventxml

{

public static void Bindchangeing ()

{

XElement Xele = new XElement ("Root");

Xele. changing + = xele_changing;

Xele. Changed + = xele_changed;

Xele. ADD (New XElement ("Item", "123"));

var item = Xele. Element ("Item");

Item. ReplaceWith (New XElement ("Item", "2"));

item = Xele. Element ("Item");

Item. Remove ();

Console.readkey ();

}

static void Xele_changed (object sender, Xobjectchangeeventargs e)

{

XElement ele = sender as XElement;

Console.WriteLine (String.Format ("completed {0}-{1}", Ele. Name, E.objectchange));

}

static void Xele_changing (object sender, Xobjectchangeeventargs e)

{

XElement ele = sender as XElement;

Console.WriteLine (String.Format ("In Progress {0}-{1}", Ele. Name, E.objectchange));

}

}

In addition to the Declaration, Running GuestArticles are original, reproduced please link to the form of the address of this article
A detailed explanation of LINQ to XML in C #

This address: http://www.paobuke.com/develop/c-develop/pbk23152.html






Related content C # methods for detecting text file encoding C # Methods of obtaining CPU numbers C # methods for solving the maximum and minimum values in N # methods for array initialization and array element copying in C #
C # Operations for PowerPoint Methods C # implements the method of obtaining absolute address of a website based on the relative address given C # hosting process (Vshost.exe) in VS2005. C # The way to realize the value of moving the mouse to the graph

A detailed explanation of LINQ to XML in C #

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.