XElement value in C#

前端 未结 3 1477
天涯浪人
天涯浪人 2021-02-14 08:31

How to get a value of XElement without getting child elements?

An example:



    someValue
            


        
3条回答
  •  我在风中等你
    2021-02-14 08:54

    You can do it slightly more simply than using Descendants - the Nodes method only returns the direct child nodes:

    XElement element = XElement.Parse(
        @"somevalue12");
    var firstTextValue = element.Nodes().OfType().First().Value;
    

    Note that this will work even in the case where the child elements came before the text node, like this:

    XElement element = XElement.Parse(
        @"12some value");
    var firstTextValue = element.Nodes().OfType().First().Value;
    

提交回复
热议问题