Build XML document using Linq To XML
- by JasonDR
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?