0

I have this string,and getting an error

string text =

<root><Info id="inseID">17</Info><note><123comments></note></root>

I wanted to convert it to

<root><Info id="inseID">17</Info><note>&lt;123comments&gt;</note></root>
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
shololauy
  • 13
  • 1
  • 1
  • 3
  • why dont you simply use https://learn.microsoft.com/en-us/dotnet/api/system.string.replace?view=netcore-3.1 – TAHA SULTAN TEMURI Jul 15 '20 at 15:36
  • 1
    How are you writing it currently? any xml writer, serializer, or DOM API is going to get this right without you having to do anything; if you're building xml by concatenating strings, I'm mostly going to say "don't do that" – Marc Gravell Jul 15 '20 at 15:36
  • Welcome to Stack Overflow. Please give us more context. Are you really *passed* invalid XML and then have to do something with it? Or do you actually have a string of "<123comments>" that you wish to use as a value in the XML? If you can provide a [mcve] that accurately reflects your situation, that would be very useful. – Jon Skeet Jul 15 '20 at 15:36
  • There is no escape characters. Just edit (or added the <123comments> correctly). – jdweng Jul 15 '20 at 15:38
  • I updated the context, sorry about that. It is an xml, but it was converted to string. If I replace it, it will replace all, is there a way just to replace the value? – shololauy Jul 15 '20 at 15:40
  • I rolled back the edit - please don't use images for code; I've already fixed the formatting for you – Marc Gravell Jul 15 '20 at 15:40
  • "is there a way just to replace the value?" - the problem there is: what you have is not valid xml, so you can't use an xml tool to fix it; so that leaves text tools - and that [doesn't end very well](https://stackoverflow.com/a/1732454/23354); ultimately, you need to fix this *before* it gets corrupted – Marc Gravell Jul 15 '20 at 15:42
  • XML is text. This isn't XML though, it contains malformed parts. How was it created? How do you know that `<123comments>` should be escaped? Why not use `<123comments/>`? The code that produced this text has a bug that needs to be fixed. You can't guess what the correct XML would be, *especially* in this instance. – Panagiotis Kanavos Jul 15 '20 at 15:42
  • yeah it's a long xml, that was passed as a string to replace the `< >`,and then convert it again to `< >`. but the `QA <123 comments> `in note, that breaks the saving in SQL. – shololauy Jul 15 '20 at 15:45
  • 1
    You still need to fix the *producer* code. The answer shows how to do that with LINQ to XML, but the XmlDocument-related classes would also escape text before saving it – Panagiotis Kanavos Jul 15 '20 at 16:16

1 Answers1

1

Use linq to xml.

var text = "<root><Info id=\"inseID\">17</Info><note></note></root>";
var xml = XElement.Parse(text);
xml.Element("note").Add("<123comments>");
//string result = xml.ToString(); // will be escaped
Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49