views:

559

answers:

1

I want to set the value/children of an element that may or may not already exist. If the element doesn't exist, I want to have it automagically created for me.

This way, my code only has to worry about the contents of the element... not whether or not it already exists. (By the time I'm done with it, it's guaranteed to exist).

Does this functionality already exist in LINQ-to-XML? I haven't found it yet, and am considering writing my own method.

+3  A: 

Here's what I have so far:

public static IEnumerable<XElement> ElementsOrCreate(this XElement parent, XName name)
{
    IEnumerable<XElement> elements = parent.Elements(name);
    if (!elements.Any())
    {
      XElement element = new XElement(name);
      parent.Add(element);
      elements = new XElement[] { element };
    }
    return elements;
}

Note that the first argument (for the extension) is an XElement, not an XContainer like System.Xml.Linq.Extensions.Elements. The only other non-XElement XContainer is XDocument, and this method doesn't work (and doesn't make much sense) for an XDocument.

Craig Walker