Build XML document using Linq To XML
Posted
by JasonDR
on Stack Overflow
See other posts from Stack Overflow
or by JasonDR
Published on 2010-05-05T03:55:12Z
Indexed on
2010/05/05
3:58 UTC
Read the original article
Hit count: 445
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?
© Stack Overflow or respective owner