Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XElement value in C#

Tags:

c#

xml

xelement

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.

like image 553
shadeglare Avatar asked Jul 11 '10 19:07

shadeglare


2 Answers

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;
like image 145
Jon Skeet Avatar answered Sep 21 '22 07:09

Jon Skeet


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);
}
like image 30
John Saunders Avatar answered Sep 21 '22 07:09

John Saunders