tags:

views:

123

answers:

2

I want to modify all the text nodes using some functions in C#. I want to insert another xml subtree created from some string.

For example, I want to change this

<root>
this is a test
</root>

to

<root>
this is <subtree>another</subtree> test
</root>

I have this piece of code, but it inserts text node, I want to create xml subtree and insert that instead of plain text node.

List<XText> textNodes = element.DescendantNodes().OfType<XText>().ToList();
foreach (XText textNode in textNodes)
{
    String node = System.Text.RegularExpressions.Regex.Replace(textNode.Value, "a", "<subtree>another</subtree>");
    textNode.ReplaceWith(new XText(node));
}
+2  A: 

You can split the original XText node into several, and add an XElement in between. Then you replace the original node with the three new nodes.

List<XNode> newNodes = Regex.Split(textNode.Value, "a").Select(p => (XNode) new XText(p)).ToList();

newNodes.Insert(1, new XElement("subtree", "another")); // substitute this with something better

textNode.ReplaceWith(newNodes);
Jonatan Lindén
there can be many 'a' and 'another' and 'a' are not constant, also value of 'another' depends on value of 'a'. Is there a better solution, where I can just create a subnode from string.
Priyank Bolia
also this is wrong, what if there is no 'a', then also you will insert an 'another' into it.
Priyank Bolia
also this won't compile, as the typecasting won't happen from 'System.Collections.Generic.List<System.Xml.Linq.XText>' to 'System.Collections.Generic.List<System.Xml.Linq.XNode>'
Priyank Bolia
Also I couldn't find the Insert method.
Priyank Bolia
Yes, insert is not the way to go here (thereby the comment), but it was just to show that you add an XElement to the collection, and then replaces the old node with a collection of new nodes.I had a forgotten a cast, that's why it didn't work, so now it should be ok. And what do you mean that you couldn't find the Insert method? It's a member of the List class.
Jonatan Lindén
A: 

I guess CreateDocumentFragment is much easier, though not LINQ, but the idea to use LINQ is ease only.

Priyank Bolia