如何获取 XElement
的值没有得到子元素?
一个例子:
<?xml version="1.0" ?>
<someNode>
someValue
<child>1</child>
<child>2</child>
</someNode>
如果我将 XElement.Value 用于 <someNode>
我得到 "somevalue<child>1</child><child>2<child>"
字符串,但我只想获得没有 "<child>1</child><child>2<child>"
的“somevalue”子串。
最佳答案
你可以比使用 Descendants
更简单一些 - Nodes
方法只返回直接子节点:
XElement element = XElement.Parse(
@"<someNode>somevalue<child>1</child><child>2</child></someNode>");
var firstTextValue = element.Nodes().OfType<XText>().First().Value;
请注意,即使在子元素出现在文本节点之前的情况下,这也会起作用,如下所示:
XElement element = XElement.Parse(
@"<someNode><child>1</child><child>2</child>some value</someNode>");
var firstTextValue = element.Nodes().OfType<XText>().First().Value;
关于c# - C# 中的 XElement 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3224417/