0

I am wondering, how can I add a new XElement by using a if/else statement?

For example...

XDocument document = XDocument.Load(this.XMLFile);
document.Element("currentjobs").Add(
     new XElement("job",
            new XElement("date", now.ToShortDateString() + " " + now.ToUniversalTime()),
            new XElement("name", job.name)
            )
     );

Now if I wanted to add a new XElement in that XML by using if/else statement from a variable I have in C#.

The if else statement would be like...

if(job.status == 2)
{
//add XML...
}

How would I go ahead and do this?

Kyle
  • 53
  • 7

1 Answers1

3

From Valid Content of XElement and XDocument Objects, you can pass null to the XElement constructor, and it will not affect the XML tree, so:

XDocument document = XDocument.Load(this.XMLFile);
document.Element("currentjobs").Add(
     new XElement("job",
            new XElement("date", now.ToShortDateString() + " " + now.ToUniversalTime()),
            new XElement("name", job.name),
            optionalElement ? new XElement("optional", "value") : null
            )
     );
John Saunders
  • 160,644
  • 26
  • 247
  • 397