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.
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();
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# |