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 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.