Assuming I have a xdocument called xd, with the following xml already created.
<Alert>
<Source>
<DetectTime>12:03:2010 12:22:21</DetectTime>
</Source>
</Alert>
How would I be able to add another Alert element, such that the xml becomes:
<Alert>
<Source>
<DetectTime>12:03:2010 12:22:21</DetectTime>
</Source>
</Alert>
<Alert>
</Alert>
Adding an additional elements seems to be fairly easy, but when adding in a top level element it excepts.
Your desired XML structure is invalid; you need a root element in order to add another “Alert” node. The following code shows how to add it when a root node exists:
The above code produces
<Alert />since no child nodes are added to it (this will change once you add to it). If you want the closing tag as you have shown you can usexdoc.Root.Add(new XElement("Alert", String.Empty));instead.To verify that your desired output has an invalid structure you can try parsing it using
XDocument.Parsesimilar to what I’ve shown above.