Click here to Skip to main content
15,885,702 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi , i hav a xml file

XML
<parent>
<child>
<tag>AAA</tag>
<att>BBB</att>
</child>
<parent>



how to get the value of <tag> & <att> using Linq

I am new to xml and linq
plz help!
Posted
Updated 25-Feb-13 1:53am
v2

1 solution

You need to reference at least these two namespaces:
C#
using System.Linq;
using System.Xml.Linq;

And try this code:
C#
var xml = @"
<parent>
 <child>
  <tag>AAA</tag>
  <att>BBB</att>
 </child>
 <child>
  <tag>CCC</tag>
  <att>DDD</att>
 </child>
</parent>";

var xDoc = XDocument.Parse(xml);

var query = from i in xDoc.Root.Descendants("child")
            select new
            {
                Tag = i.Descendants("tag").First().Value,
                Att = i.Descendants("att").First().Value
            };

var items = query.ToArray();

Remember, that you can use any LINQ extension methods, like Select, Single, Count, Sum, etc.
 
Share this answer
 
Comments
rohit24c 26-Feb-13 3:47am    
this code returns me
items[0] as tag: "ABC" & att:"BBB"
but i want only the value [0] ABC,BBB
Matej Hlatky 26-Feb-13 4:05am    
There is no ABC value. My example shows, that you actually get collection of objects with tag and att properties.
Try to call FirstOrDefault extension method on the query to get only first record.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900