XML Parsing - Linq
-
Thursday, February 14, 2013 8:48 AM
Hi,
I am stuck up in parsing an XML using Linq,
My XMl file is as below... I want to get all the '<File>' node values which matches a specifi <File> node in the <Files> node
For eg: I want to get "fusionserver.log, fmvifmonitor.log, event.log" as a result, when the user passes 'messages' as the input
<?xml version="1.0" encoding="utf-8" ?> <LogFiles> <Files> <File>messages</File> <File>fusionserver.log</File> <File>fmvifmonitor.log</File> <File>event.log</File> <File>ajscanner.log</File> </Files> <Files> <File>cifsservicemonitor.log</File> <File>quotamonitor.err</File> <File>Iad.log</File> <File>ibrcfrworkerd.log</File> </Files> </LogFiles>
I tried with the below code, it throws exception 'Expression can not contain lambda expressions'
f.Root.Descendants("Files").Where(x => x.Element("File").Value = "messages").Select(x => x.Element("File").Value);
Please help me on this!- Moved by Mike FengMicrosoft Contingent Staff, Moderator Friday, February 15, 2013 7:09 AM
All Replies
-
Thursday, February 14, 2013 9:14 AM
Try this code
XElement root = XElement.Parse(xml); var query = from n in root.Descendants("Files")
where n.Descendants("File").Any(f => f.Value == "messages")
from f in n.Descendants("File")
select f.Value; string result = string.Join(", ", query); Console.WriteLine(result); Console.ReadLine();
Miha Markic [MVP C#] http://blog.rthand.com
- Edited by Miha MarkicMVP Thursday, February 14, 2013 9:17 AM
-
Thursday, February 14, 2013 11:02 AM
Thanks you!
I can not hardcode 'messages' in the LinQ query. So I had to rewrite the code as below...
var ff = XDocument.Load("LogsRelationship.xml"); Expression<Func<XElement, bool>> whereClause = a => a.Element("File").Value == strFileName; var query = ff.Descendants("Files").Where(whereClause).Select(x => x.Parent); foreach (XElement item in query.Descendants("Files")) { foreach (XElement it in item.Elements("File")) { Console.Write(it.Value); } }But this gives error "cannot convert from 'System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>' to 'System.Linq.IQueryable<System.Xml.Linq.XElement>' " in the below line
var query = ff.Descendants("Files").Where(whereClause).Select(x => x.Parent);Please help me!
-
Thursday, February 14, 2013 11:05 AM
string criteria = "messages"; ... where n.Descendants("File").Any(f => f.Value == criteria) ...
This would work as well.
Miha Markic [MVP C#] http://blog.rthand.com
- Proposed As Answer by Mike FengMicrosoft Contingent Staff, Moderator Friday, February 15, 2013 7:08 AM
- Marked As Answer by Alexander SunModerator Thursday, February 28, 2013 5:16 AM

