views:

288

answers:

3

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.

A: 

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);
}
John Saunders
Great thanks. In my program I'm needed in full enumeration of xml nodes and changes every values. With your sample I'm not needed in a recursive enum of xml nodes.
MaxFX
@MaxFX: This will still recursively enumerate all nodes within the element though. It's hidden, but it's still happening. See my answer for a way of avoiding that.
Jon Skeet
A: 

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;
ckramer
+4  A: 

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;
Jon Skeet