I’m trying to build an XML file that reads the content to put inside from a list:
List<Snack> trashFoods
When I create the XML file, it would be something like this:
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment(""),
new XElement("Snacks",
trashFoods.Select(snack =>
new XElement("Type", snack.Type),
new XElement("Name", snack.Name)
),
)
What I want to, and I am unable to do is something like putting conditionals inside the construction of the XML file. Similar to this:
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment(""),
new XElement("Snacks",
trashFoods.Select(snack =>
new XElement("Type", snack.Type),
if(snack.Type == "Doritos")
{
new XElement("GotSauce", snack.Sauce),
}
new XElement("Name", snack.Name)
),
)
Is this such a thing even possible with LINQ to XML even if the syntax is not the same?
LINQ to XML objects are not immutable, so you can rewrite your declarative code into imperative one using
Add():It’s not very pretty, but it work. Another approach would be to extract the conditional code into a method using
yield return:This looks better, but it splits code that probably should be together.