gpt4 book ai didi

c# - C# 中的 XElement 值

转载 作者:数据小太阳 更新时间:2023-10-29 01:43:06 26 4
gpt4 key购买 nike

如何获取 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com