XElement value in C#

2019-03-26 17:26发布

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.

标签: c# xml xelement
3条回答
Lonely孤独者°
2楼-- · 2019-03-26 18:02

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;
查看更多
我只想做你的唯一
3楼-- · 2019-03-26 18:02

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);
}
查看更多
别忘想泡老子
4楼-- · 2019-03-26 18:05

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;
查看更多
登录 后发表回答