tags:

views:

195

answers:

1

Hi All, I have a xml structure similar to below one:

              <test>
                <test1>test1 value</test1>
               </test>

Now I am reading the value of node using below LINQ to xml code.

        var test = from t in doc.Descendants("test") select t.Element("test1").Value;
        Console.WriteLine("print single node value");
        foreach (var item in test)
        {
            Console.WriteLine(item);   
        }

above code works fine, but here I have one single node, but to retrive value I am using foreach loop, which I dont think is good..any better way of doing the same thing without a foreach loop Thanks.

+2  A: 

Try something like this:

using System;
using System.Linq;
using System.Xml.Linq;

public class Example
{
    static void Main()
    {
        String xml = @"<test>
                <test1>test1 value</test1>
                        </test>";

        var test = XElement.Parse(xml)
                .Descendants("test1")
                .First()
                .Value;

        Console.WriteLine(test);
    }
}
Andrew Hare
this will/ is working , but i am reading the values from a xml file.
Wondering
@Wondering - Then all you need to do is change `XElement.Parse(xml)` to `XElement.Load(pathToYourFile)`.
Andrew Hare
ok, as per my code, i changed it to var res = doc.Descendants("test1").First().Value; and it worked.thanks for all ur help
Wondering