简体   繁体   English

C#中的XElement值

[英]XElement value in C#

How to get a value of XElement without getting child elements? 如何在不获取子元素的情况下获取XElement的值?

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. 如果我对<someNode>使用XElement.Value,我会得到"somevalue<child>1</child><child>2<child>"字符串,但我想只获得“somevalue”而没有"<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: 您可以比使用Descendants更简单地执行此操作 - 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. 其中XElement是表示<someNode>元素的元素。

You can specifically ask for the first text element (which is "somevalue"), so you could also do: 你可以特别要求第一个文本元素(这是“somevalue”),所以你也可以这样做:

var value = XElement.Descendents.OfType<XText>().First().Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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