How to add value between tags using XElement?

atconway picture atconway · Jan 23, 2013 · Viewed 7.3k times · Source

I have looked a bunch of XML samples using XDocument and XElement but they all seem to have self closing tags like <To Name="John Smith"/>. I need to do the following:

<To Type="C">John Smith</To>

I thought the following would work and tried to look at the object model of the Linq.XML class, but I'm off just a tad (see line below that is not working)

new XElement("To", new XAttribute("Type", "C")).SetValue("John Smith")

Any assistance on how to get the XML formed properly is appreciated, thanks!

Answer

Jon Skeet picture Jon Skeet · Jan 23, 2013

I'd use:

new XElement("To", new XAttribute("Type", "C"), "John Smith");

Any plain text content you provide within the XElement constructor ends up as a text node.

You can call SetValue separately of course, but as it doesn't return anything, you'll need to store a reference to the element in a variable first.