I am just trying to read some details from an XML file, part of which looks like this:
<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>
I have several of these ‘appender’ nodes in my XML file. The following code loops through each ‘appender’ node. Within each ‘appender’ I want to pick out the param node with name “File” and check if the value is equal to what I am looking for.
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
}
}
However my code is not printing anything out, so I think possibly the ‘where’ part of my LINQ query is incorrect, can anybody spot where I am going wrong?
You’re calling
XAttribute.ToString(). Try usingXAttribute.Valueinstead, or just cast to a string.ToString()will returnvalue="C:\\Logs\\File.log"– the name and the value – whereas you just want the value:Personally I wouldn’t bother with a query expression here, btw:
EDIT: Additionally, as others have said, you want to have single backslashes in the XML file.