1

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 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

5 Comments

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.
also this is wrong, what if there is no 'a', then also you will insert an 'another' into it.
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>'
Also I couldn't find the Insert method.
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.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.