Click here to Skip to main content
12,621,430 members (30,172 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C# LINQ C#4.0
Hi , i hav a xml file

<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 25-Feb-13 2:51am
Updated 25-Feb-13 2:53am
v2

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

You need to reference at least these two namespaces:
using System.Linq;
using System.Xml.Linq;
And try this code:
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.
  Permalink  
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web01 | 2.8.161128.1 | Last Updated 25 Feb 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100