0

The xml element below

<text>this is some text <content><link attr="someattr">text to appear in link</link></content> . this is the end of the text</text>

needs to transform to

<p>this is some text <a attr="someattr">text to appear in link</a> . this is the end of the text</p>

I have a method that takes in "content" element as parameter and returns the "a" element. I cannot figure out how to display the text from "text" element and the link at the same time.

2
  • I you need to transform a text - perhaps Linq-to-Xml is not the right way to go. You should look into RegularExpressions Commented Sep 11, 2014 at 6:42
  • this is not text but xml. I have only shared a snippet of the xml. Commented Sep 11, 2014 at 22:36

1 Answer 1

1

You can try this way :

var xml =
    @"<text>this is some text <content><link attr=""someattr"">text to appear in link</link></content> . this is the end of the text</text>";
var text = XElement.Parse(xml);
//change <text> to <p>
text.Name = "p";

var content = text.Element("content");
var link = content.Element("link");

//change <link> to <a>
link.Name = "a";

//move <a> to be after <content>
content.AddAfterSelf(link);

//remove <content> tag
content.Remove();

//print result
Console.WriteLine(text.ToString());
Sign up to request clarification or add additional context in comments.

2 Comments

This actually works but when the xml contains more than 1 "content" elements, then I cannot get it to work.
Instead of removing element using content.Remove(), I tried text.Elements("content").Remove(); which did the trick. I also ran the previous code in a foreach loop to add the "a" elements appropriately.

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.