Reputation: 27384
I am looking for a nice way to save / load the following. I want to save as XML and ideally looking to use LiNQ (namely to help me learn LINQ)
I don't know how to do nested linq writes though. Can anyone help?
/// <summary>
///
/// </summary>
public class ErrorType
{
List<ErrorType> _childErrors;
public String Name { get; set; }
public bool Ignore { get; set; }
public List<ErrorType> ChildErrors { get; protected set; }
}
/// <summary>
///
/// </summary>
public class ErrorList
{
public List<ErrorType> ChildErrors { get; protected set; }
public void Save()
{
}
public void Load()
{
}
}
Essentially the ErrorList contains a top level list of Errors, each error can have children. The XML output should look something like:
<ErrorList>
<ErrorName1 Ignore="false">
<ChildErrorName1 Ignore="true">
<ChildErrorName2 Ignore="false" />
</ChildErrorName1>
</ErrorName1>
<ErrorList>
If anyone could help that would be great. Thanks
Upvotes: 0
Views: 662
Reputation: 1500515
Okay, I think I see what you're after now. Try this:
// Need to declare in advance to call within the lambda.
Func<ErrorType, XElement> recursiveGenerator = null;
recursiveGenerator = error => new XElement
(error.Name,
new XAttribute("Ignore", error.Ignore),
error.ChildErrors.Select(recursiveGenerator));
var errorList = new XElement
("ErrorList", errors.ChildErrors.Select(recursiveGenerator));
Here's a complete example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
public class ErrorType
{
public String Name { get; set; }
public bool Ignore { get; set; }
public List<ErrorType> ChildErrors { get; protected set; }
public ErrorType()
{
ChildErrors = new List<ErrorType>();
}
}
public class ErrorList
{
public List<ErrorType> ChildErrors { get; protected set; }
public ErrorList()
{
ChildErrors = new List<ErrorType>();
}
}
public class Test
{
public static void Main()
{
var childError2 = new ErrorType {
Name = "ChildErrorName2", Ignore=false };
var childError1 = new ErrorType {
Name = "ChildErrorName1", Ignore=true,
ChildErrors = { childError2 }
};
var mainError = new ErrorType {
Name = "ErrorName1", Ignore=true,
ChildErrors = { childError1 }
};
var errorList = new ErrorList { ChildErrors = { mainError } };
// Need to declare in advance to call within the lambda.
Func<ErrorType, XElement> recursiveGenerator = null;
recursiveGenerator = error => new XElement
(error.Name,
new XAttribute("Ignore", error.Ignore),
error.ChildErrors.Select(recursiveGenerator));
var element = new XElement
("ErrorList",
errorList.ChildErrors.Select(recursiveGenerator);
Console.WriteLine(element);
}
}
Upvotes: 1
Reputation: 24385
Have a look at this. It should be what you are looking for. No LINQ thought but rather nice and easy way of outputting XML.
The bottom line though is to use XmlSerializer.
Upvotes: 0