简体   繁体   中英

XElement value in C#

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

An example:

<?xml version="1.0" ?>
<someNode>
    someValue
    <child>1</child>
    <child>2</child>
</someNode>

If i use XElement.Value for <someNode> I get "somevalue<child>1</child><child>2<child>" string but I want to get only "somevalue" without "<child>1</child><child>2<child>" substring.

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;

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM