views:

143

answers:

1

Given the following code:

    string xml = "";
    //alternativley: string xml = "<people />";

    XDocument xDoc = null;

    if (!string.IsNullOrEmpty(xml))
    {
        xDoc = XDocument.Parse(xml);
        xDoc.Element("people").Add(
            new XElement("person", "p 1")
        );
    }
    else
    {
        xDoc = new XDocument();
        xDoc.Add(new XElement("people",
            new XElement("person", "p 1")
            ));
    }

As you can see, if the xml variable is blank, I need to create the rood node manually, and append the person the root node, whereas if it is not, I simple add to the people element

My question is, is there any way to generically create the document, where it will add all referenced node automatically if they do not already exists?

+1  A: 

You mean a version of XContainer.Element which adds an element if it's not already present? Not that I'm aware of... although I guess you could write one:

public static XElement FindOrAdd(this XContainer container, XName name)
{
    XElement ret = container.Element(name);
    if (ret == null)
    {
        ret = new XElement(name);
        container.Add(ret);
    }
    return ret;
}
Jon Skeet