C # Foundation Consolidation (3)-linq to XML read XML

Source: Internet
Author: User

Record some of the methods of reading XML, so as not to forget the use of time, but also to take the time to find.

One, the traditional notation reads the XML

Now I have an XML file as follows:

Now I'm looking for the Id of this person named "Harry" and Sex (Sex) and age (ages)

Code:

 Static voidMain (string[] args) {XDocument Xdoc= Xdocument.load ("4.xml");//Load XMLList<xelement> Eles =NewList<xelement> ();//Used toget a collection of nodes that meet the criteriaXElement ele = Xdoc. Element ("Root");//Get root node            stringNametxt ="Harry";//criteria to look forTraditionalreadxml (Ele,eles,nametxt);//find eligible data to add to Eles's collection            foreach(XElement IteminchEles//traverse the data to be traced, output{Console.WriteLine ("Id:{0},name:{1},sex:{2},age:{3}", item. Attribute ("ID"). Value,item. Element ("name"). Value,item. Element ("Sex"). Value,item. Element (" Age").            Value);        } console.readkey (); }        /// <summary>        ///Traditional Read XML/// </summary>        /// <param name= "Ele" >The data under which node is found</param>        /// <param name= "Eles" >Collection holds the data that matches</param>        /// <param name= "Nametxt" >name to look for</param>        Private Static voidTraditionalreadxml (XElement ele,list<xelement> eles,stringnametxt) {            //First, traverse all the child nodes under the Ele, note that it is a child node and cannot find the lower level node            foreach(XElement IteminchEle. Elements ()) {//judge whether the name of this element is not name, if it is name, see if the content is Nametxt                if(item. Name.localname = ="name")                {                    if(item. Value = =nametxt) {                        //a node that meets the criteria, taking its parentEles. ADD (item.                    Parent); }                }                //If the item has a child node in it, it will recursivelytraditionalreadxml (item, Eles, Nametxt); }        }

The results of the execution code are:

Second, LINQ reads XML

Change the code above to:

 Static voidMain (string[] args) {XDocument Xdoc= Xdocument.load ("4.xml");//Load XMLList<xelement> Eles =NewList<xelement> ();//get a collection of nodes that meet the criteria            stringNametxt ="Harry";//criteria to look for//get the node that meets the criteria           var query = from S in Xdoc. Descendants () where s.name.localname = = "Name" && s.value ==nametxt Select S.parent;            foreach(XElement IteminchQuery//adding eligible nodes to the Eles collection{eles.            ADD (item); }            foreach(XElement IteminchEles//traverse the data to be traced, output{Console.WriteLine ("Id:{0},name:{1},sex:{2},age:{3}", item. Attribute ("ID"). Value,item. Element ("name"). Value,item. Element ("Sex"). Value,item. Element (" Age").            Value); } console.readkey ();
}

The bold Place is written in LINQ, and they are implemented the same way, which is much simpler than the normal notation.

Third, LINQ query Lambda notation

Change the code to:

 Static voidMain (string[] args) {XDocument Xdoc= Xdocument.load ("4.xml");//Load XMLList<xelement> Eles =NewList<xelement> ();//get a collection of nodes that meet the criteria            stringNametxt ="Harry";//criteria to look for//iterate over the nodes to add eligible additions to the Eles collection            foreach  (XElement i in  Xdoc. Descendants (). Where (E=>{ if  (e.name.localname== " name  "   if  (E.value==nametx T) { return  tr UE  ; }}  return  false  foreach(XElement IteminchEles//traverse the data to be traced, output{Console.WriteLine ("Id:{0},name:{1},sex:{2},age:{3}", item. Attribute ("ID"). Value,item. Element ("name"). Value,item. Element ("Sex"). Value,item. Element (" Age").            Value);        } console.readkey (); }

The above is three ways to read XML, can be used according to their preferred method.

C # Foundation Consolidation (3)-linq to XML read XML

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.