从 LINQ 到 XML 查询中获取单个字符串

本文关键字:获取 单个 字符串 查询 LINQ XML | 更新日期: 2023-09-27 17:59:06

这是我想要做的:

string parseCode = from x in xml.Descendants("LogType")
                   where x.Attribute("ID").Value == string)ddlHistoryLogDefinitions.SelectedValue
                   select x.Attribute("ParseCode").Value;

但这会产生错误:">无法将类型'System.Collections.Generic.IEnumerable'隐式转换为'字符串'">

x.Attribute("ParseCode")只有一个值,但它坚持返回类型 IEnumerable<string> 。如何将该值提取到字符串中?

编辑:感谢您的回复。以下是对我有用的方法:

string parseCode = (from x in xml.Descendants("LogType")
                    where x.Attribute("ID").Value == (string) ddlHistoryLogDefinitions.SelectedValue
                    select (string) x.Attribute("ParseCode").Value).FirstOrDefault();

这个技巧是在 .FirstOrDefault((。

从 LINQ 到 XML 查询中获取单个字符串

如果您知道只有一个结果,请使用.Single选择唯一的结果:

string parseCode = (from x in xml.Descendants("LogType")
                   where x.Attribute("ID").Value == string)ddlHistoryLogDefinitions.SelectedValue
                   select x.Attribute("ParseCode").Value).Single();

分别使用 .SingleOrDefault.First 如果可能没有或多个。

查询返回集合。如果您需要找到的第一个LogType节点,则可以执行以下操作:

string parseCode = xml.Descendants("LogType")
    .Where(x => x.Attribute("ID").Value == (string)ddlHistoryLogDefinitions.SelectedValue)
    .Select(arg => x.Attribute("ParseCode").Value)
    .FirstOrDefault();

如果未找到元素,将返回null