How to read xml node (single) value using linq to xml

I have an xml structure similar to the one below:

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

      

Now I am reading node value 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 restore value i use foreach loop which i don't think is good .. best to do same without foreach loop Thanks.

+2


a source to share


2 answers


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);
    }
}

      

+9


a source


you can also try to provide the path to the XML file like below:



 XElement xmldoc = XElement.Load("filePath");
        var nodeValueFromXMlFile = xmldoc
             .Descendants("node name")
             .First()
             .Value;
        System.Console.WriteLine(nodeValueFromXMlFile);

      

0


a source







All Articles