tags:

views:

195

answers:

1

I need to wrap up all the text thats in a large XElement tree, into Elements. For example:

<element1>hello<element2>there</element2>my friend</element1>
Becomes
<element1><text value=”hello”/><element2><text value=”there”/></element2><text value=”my friend”/></element1>
+4  A: 

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 :)

Jon Skeet