C# 中的 XElement 值 [英] XElement value in C#
本文介绍了C# 中的 XElement 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在不获取子元素的情况下获取XElement
的值?
How to get a value of XElement
without getting child elements?
示例:
<?xml version="1.0" ?>
<someNode>
someValue
<child>1</child>
<child>2</child>
</someNode>
如果我将 XElement.Value 用于
我得到 "somevalue
字符串但我只想得到没有 "<child>1</child><child>2<child>"
子字符串的somevalue".
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.
推荐答案
你可以比使用 Descendants
稍微简单一点 - Nodes
方法只返回直接子节点节点:
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;
这篇关于C# 中的 XElement 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文