I think this does what you're after:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
string xml = "<element1>hello<element2>there"
+ "</element2>my friend</element1>";
XElement element = XElement.Parse(xml);
List<XText> textNodes = element.DescendantNodes()
.OfType<XText>()
.ToList();
foreach (XText textNode in textNodes)
{
textNode.ReplaceWith (new XElement
("text", new XAttribute("value", textNode.Value)));
}
Console.WriteLine(element);
}
}
It's possible that you could do the replacement in the "live" query, but I'm always wary of manipulating a document while iterating over it - I don't know enough about LINQ to XML to be sure that it would work. Copying all the text node references to a list first seems safer to me :)