how to get child node value in xml using c#

Recently i need to get specific child node values from XML string in C#.


After spending some time i found a best way to parse the xml string to objects.

step 1 :
Include namespace
using System.Linq;

step 2:
Load xmlstring to XDocument, mean parse the string XDocument

step 3: 
By using linq with Descendants you can read specific child node values from xml string. 

READ CHILD NODES VALUES FROM XML WITH EXAMPLE


string s = @"<Root>
                        <Persons>
                            <Person ID=""1"">
                           <Name>Mishal</Name>
                            <Phone>860 9555 788</Phone>
                            <Email>abc@ac.com</Email>
                            </Person>
                            <Person>
                            <Name>Andy</Name>
                            <Phone>866 9555 788</Phone>
                            <Email>abc@abc.com</Email>
                            </Person>
                            </Persons>
                        </Root>";

            XDocument xmlString = XDocument.Parse(s);

            var root = (from obj in xmlString.Descendants("Person")
                        select new
                        {
                            Name = (string)obj.Element("Name"),
                            Phone = (string)obj.Element("Phone"),
                            Email = (string)obj.Element("Email")
                        }).ToList();

Read child nodes from xml string in C#

how to load xml string to xdocument

Today i have faced a situation that have to load xml string to XDocument.

But the Load method of XDocument doesn't support the string as a input parameter.

XDocument has another method called XDocument.Parse(xml), this method will accept xml string and parse them into an XDocument.

Example

string xmlString=  
@"<Root>  
    <ChildNode1>Value 1</Child>  
    <ChildNode2>Value 2</Child>  
    <ChildNode3>Value 3</Child>  
</Root>";  
XDocument xdocObj= XDocument.Parse(xmlString);  
Console.WriteLine(xdocObj);  


Hope this note sorted out your search on this issue.