0

I would like to replace a specific node with string.

It successfully replace the node but instead of "<div>", it appear "&lt;div&gt;"

What should I do to make it into "<div>"?

I have tried XElement.Parse but it will give me error as I replace node with "</div><div>"

foreach (var node in Nodes)
{
   var newElement = XElement.Parse("</div><div>");
   node.ReplaceWith(sbb.ToString);
}
Yin How
  • 89
  • 1
  • 7
  • 1
    Can you post the exact code you're using? – Marnix van Valen Nov 21 '19 at 08:17
  • Indeed, a [mcve] would really help here. It sounds like you're not really trying to replace a node with a string, but with another element - so you should build the `XElement` to replace it with. If you pass in a string, LINQ to XML will expect that you mean that to be the *text* content, which is why it's escaping the angle brackets. – Jon Skeet Nov 21 '19 at 08:28
  • You do not have XML. You have html. Xml Linq (XDocument/XElement) will not all the time with html. If you have xml embedded in html then use : System.Net.WebUtility.HtmlDecode(string xml) – jdweng Nov 21 '19 at 09:56
  • It will give me "Unexpected end tag error". Do XElement.Parse allow start with end tag? Something like this XElement.Parse("
    ");
    – Yin How Nov 22 '19 at 01:30

1 Answers1

0

Use the following

XElement foo = XElement.Parse("<div>example</div>");

foo.ReplaceNodes(XElement.Parse("<div>" + otherMarkUp + "</div>").Nodes()); 

Based on your code, you should replace with the newElement.

foreach (var node in Nodes)
{
   var newElement = XElement.Parse("<div></div>");
   node.ReplaceWith(newElement);
}

If the above does not work, please share some more code to work on it.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61