简体   繁体   中英

Build XML document using Linq To XML

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM