XElement value in C#

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

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

An example:



    someValue
            


        
相关标签:
3条回答
  • 2021-02-14 08:53

    There is no direct way. You'll have to iterate and select. For instance:

    var doc = XDocument.Parse(
        @"<someNode>somevalue<child>1</child><child>2</child></someNode>");
    var textNodes = from node in doc.DescendantNodes()
                    where node is XText
                    select (XText)node;
    foreach (var textNode in textNodes)
    {
        Console.WriteLine(textNode.Value);
    }
    
    0 讨论(0)
  • 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(
        @"<someNode>somevalue<child>1</child><child>2</child></someNode>");
    var firstTextValue = element.Nodes().OfType<XText>().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(
        @"<someNode><child>1</child><child>2</child>some value</someNode>");
    var firstTextValue = element.Nodes().OfType<XText>().First().Value;
    
    0 讨论(0)
  • 2021-02-14 09:03

    I think what you want would be the first descendant node, so something like:

    var value = XElement.Descendents.First().Value;
    

    Where XElement is the element representing your <someNode> element.

    You can specifically ask for the first text element (which is "somevalue"), so you could also do:

    var value = XElement.Descendents.OfType<XText>().First().Value;
    
    0 讨论(0)
提交回复
热议问题