我只是想从 XML 文件中读取一些详细信息,其中一部分如下所示:
<appender name="FILE" class="applications.core.logging.CustomFileAppender">
<param name="File" value="C:\\Logs\\File.log"/>
<param name="MaxBackupIndex" value="5"/>
</appender>
<appender name="FILE" class="applications.core.logging.CustomFileAppender">
<param name="File" value="C:\\Logs\\File2.log"/>
<param name="MaxBackupIndex" value="17"/>
</appender>
<appender name="FILE" class="applications.core.logging.CustomFileAppender">
<param name="File" value="C:\\Logs\\File3.log"/>
<param name="MaxBackupIndex" value="98"/>
</appender>
我的 XML 文件中有几个这样的“附加程序”节点。以下代码循环遍历每个“appender”节点。在每个“附加程序”中,我想选择名称为"file"的参数节点,并检查该值是否等于我要查找的值。
foreach (XElement node in XmlFile.Descendants("appender"))
{
IEnumerable<XElement> elements = from el in node.Elements("param")
where el.Attribute("value").ToString().Equals("C:\\Logs\\File.log"))
select el;
foreach (XElement el in elements)
{
Console.WriteLine("Found it " + el.Name);
// Now read value for MaxBackupIndex
}
}
但是我的代码没有打印出任何东西,所以我认为我的 LINQ 查询的“where”部分可能不正确,有人能发现我哪里出错了吗?
最佳答案
您正在调用 XAttribute.ToString()
。尝试改用 XAttribute.Value
,或者只是cast 到一个字符串。 ToString()
将返回 value="C:\\Logs\\File.log"
- 名称和值 - 而您只需要值:
var elements = from el in node.Elements("param")
where (string) el.Attribute("value") == "C:\\Logs\\File.log"
select el;
我个人不会在此处使用查询表达式,顺便说一句:
var elements = node.Elements("param")
.Where(el => (string) el.Attribute("value") == "C:\\Logs\\File.log")
编辑:此外,正如其他人所说,您希望在 XML 文件中使用单个反斜杠。
关于c# - LINQ To XML 中的“Where”子句未选择任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10622767/