简单的 C# Linq to Xml

Simple C# Linq to Xml

我希望能够使用 C# Linq 将以下格式输出到 Xml。

<Genres>
<Genre Value="Rock" />
<Genre Value="Metal" />
</Genres>

考虑以下函数。我想评估每个参数,但只添加非空字符串的参数。

private XmlElement createGenresXml(string str1 = "", string str2 = "Rock", string str3 = "Metal", string str4 = "")
{
    'Return XmlElement should look like the Xml above.
}

谢谢! \m/ \m/

    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;
    }

向 XmlElement 的转换借鉴自 here: