Reputation: 327
I would like to be able to output the following format using C# Linq to Xml.
<Genres>
<Genre Value="Rock" />
<Genre Value="Metal" />
</Genres>
Consider the following function. I want to evaluate each of the parameters but only add the ones that are not empty strings.
private XmlElement createGenresXml(string str1 = "", string str2 = "Rock", string str3 = "Metal", string str4 = "")
{
'Return XmlElement should look like the Xml above.
}
Thanks! \m/ \m/
Upvotes: 0
Views: 93
Reputation: 400
public XmlElement CreateGenresXml(string[] args)
{
var el = new XElement("Genres");
el.Add(args.Where(x => !string.IsNullOrWhiteSpace(x)).Select(arg => new XElement("Genre", new XAttribute("Value", arg))));
var doc = new XmlDocument();
using (var reader = el.CreateReader())
{
doc.Load(reader);
}
return doc.DocumentElement;
}
The conversion to XmlElement borrowed from here:
Upvotes: 1