How to add value between tags using XElement?

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

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

I thought the following would work and try to look at the Linq.XML class object model, but I am disconnecting (the line below, which does not work )

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

Any help on how to properly generate XML is appreciated, thanks!

+4
source share
2 answers

I would use:

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

Any text content provided in the XElement constructor ends as node text.

You can call SetValue separately, of course, but since it does not return anything, you need to first store the element reference in a variable.

+15
source

What about

  new XElement("To", new XAttribute("Type", "C"), "John Smith") 
+4
source

All Articles