Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add value between tags using XElement?

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!

like image 350
atconway Avatar asked Jan 23 '13 15:01

atconway


2 Answers

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.

like image 167
Jon Skeet Avatar answered Sep 28 '22 20:09

Jon Skeet


How about

  new XElement("To", new XAttribute("Type", "C"), "John Smith")
like image 29
Henk Holterman Avatar answered Sep 28 '22 20:09

Henk Holterman