public static class LINQExtension
{
// Flatten IEnumerables; similar to flatmap in Haskell, Scala, ...
public static IEnumerable<A> flatMap<A>(this IEnumerable<IEnumerable<A>> a)
{
return a.SelectMany(value => value);
}
}
internal class ExtractFields
{
// Extract Attributes for the Table(x) elements
internal static IEnumerable<XAttribute> FilterTables(XElement element)
{
return (from elem in element.Descendants()
where elem.Name.ToString().Contains("Table")
select elem.Descendants().Attributes()).flatMap();
}
// Load XML, extract Job matching provided name, then Filter Table(x) and
// return Attributes of their Descendant Elements.
internal static IEnumerable<XAttribute> LoadXml(String xmlPath, String jobName, String tag)
{
XDocument xdoc = XDocument.Load(xmlPath);
return (from element in xdoc.Descendants(tag)
where element.Attribute("Name").Value.Equals(jobName)
select FilterTables(element)).flatMap();
}
// foreach loop to LoadXMl and iterate through Fields
internal static void Print()
{
foreach (XAttribute field in LoadXml("myserver.xml", "Job1", "Job"))
{
// Note: we can access parental values if required, it helps to differentiate
// between fields for Table1 vs. Table2)
var table = field.Parent.Parent;
var tableAttribute = table.Attribute("IDField");
Console.WriteLine(table.Name + " / (" +
tableAttribute.Name + " = " + tableAttribute.Value + ") / " +
field.Parent.Name + " " + field.Name + " = " + field.Value + ")");
}
}
}