Louis Rhys
Louis Rhys

Reputation: 35637

How to get an XElement, and create it if it doesn't exist?

Is there a way to use something like Element method in XContainer, but will create a new XElement and return that if the Element with the specified name doesn't exist in the container?

Upvotes: 3

Views: 2986

Answers (3)

Laurent LA RIZZA
Laurent LA RIZZA

Reputation: 2975

I think you should write it yourself. It should be a static helper method.



    private static XElement GetOrCreateElement(XContainer container, string name) {
        var element = container.Element(name);
        if(element == null)
        {
           element = new XElement(name);
            container.Add(element);
        }
        return element;
    }

If you wish to use member call syntax, make it an extension method by adding "this" in front of XContainer. In this case, the method shall be in a static class with no field that you may call "XContainerExtensions".

Upvotes: 6

Jehof
Jehof

Reputation: 35544

I think that is not possible since Linq-to-XML is a query language for XML-Data and does not provide CRUD operations while querying. You have to use two steps.

First query for your element, and if i doesn´t exist you have to add your new element to your container.

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174397

No, you have to write that functionality yourself:

var element = container.Element("name");
if(element == null)
{
    element = new XElement("name");
    container.Add(element);
}

Upvotes: 0

Related Questions