gpt4 book ai didi

c# - 我对 Linq XML 查询感到困惑

转载 作者:数据小太阳 更新时间:2023-10-29 02:08:49 24 4
gpt4 key购买 nike

这是我的 XML 示例。如果 ID = 123,我想选择 SystemSetting 的值。但我无法弄清楚如何。如果 id 的值等于 123,我如何选择 SystemSetting 值?

<?xml version="1.0" encoding="utf-8" ?>
<Private>
<System>
<ID>123</ID>
<NAME>Test</NAME>
<SystemSetting>128</SystemSetting>
<SystemSettingCS>127</SystemSettingCS>
</System>
<System>
<ID>124</ID>
<NAME>Test2</NAME>
<SystemSetting>128</SystemSetting>
<SystemSettingCS>127</SystemSettingCS>
</System>
<System>
<ID>0</ID>
<NAME>Test</NAME>
<SystemSetting>5</SystemSetting>
<SystemSettingCS>250</SystemSettingCS>
</System>
</Private>

这是我尝试过的:

    var doc = XDocument.Load(Application.StartupPath+  @"\Settings.xml");
var q = from Ana in doc.Descendants("Private")
from sistem in Ana.Elements("System")
where (int)sistem.Element("ID") == 123
from assetText in Sistem.Elements("System")
select assetText.Element("SystemSetting");

MessageBox.Show(q.ToString());

感谢帮助。

最佳答案

我认为你把这件事变得比你需要的更复杂了。我认为您只需要:

var query = doc.Descendants("Private") // Or just doc.Root
.Elements("System")
.Where(x => (int) x.Element("ID") == 123)
.Select(x => x.Element("SystemSetting"))
.FirstOrDefault();

诚然,这将选择第一个 匹配元素。 query 的类型然后是XElement ;如果你取下 FirstOrDefault()部分,它将返回一个 IEnumerable<XElement> , 对于所有匹配的元素。

如果您只需要值而不是元素,您可以更改 Select到:

.Select(x => (string) x.Element("SystemSetting"))

.Select(x => x.Element("SystemSetting").Value)

(如果没有 null 元素,第一个将返回 SystemSetting;第二个将抛出异常。)

关于c# - 我对 Linq XML 查询感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13609391/

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