-1

I am passing XML data to a server from a text Box, now issue is XML is giving issues with symbols like & < |. So i want to replace these symbols with their equivalent codes.

if i use string.replace function it will replace the characters recently replaced as well.

.Replace("&", "&#38;")
.Replace("<", "&#60;")
.Replace("|", "&#124;")
.Replace("!", "&#33;")
.Replace("#", "&#35;")

As it go through complete string again and again. So &<# will become "&&#35;38;&&#35;60;"

I also tried Dictionary method:

  var replacements = new Dictionary<string, string> 
            { 
            {"&", "&#38;"}, 
            {"<", "&#60;"}, 
            {"|", "&#124;"},
            {"!", "&#33;"},
            {"#", "&#35;"}
}
var output = replacements.Aggregate(input, (current, replacement) => current.Replace(replacement.Key, replacement.Value));
return output;

But same issue here as well. I also tried string builder method, but same repeating replacement issue. Any Advise?

Nisar Afridi
  • 167
  • 1
  • 4
  • 20
  • consider using a regex. – Daniel A. White Oct 30 '16 at 17:45
  • 2
    There are well established ways to escape/unescape XML values and build XML with properly escaped values in it. There's no benefit in trying to make your own from scratch. I would provide some advise on how to go about that, but it's not entirely clear what you're trying to do (where's the code you're using to build the XML)? Focusing your question around that will probably get you much more fruitful information. – JLRishe Oct 30 '16 at 17:48
  • If you have access, you may try [HttpServerUtility.HtmlEncode](https://msdn.microsoft.com/en-us/library/w3te6wfz(v=vs.110).aspx) – Siva Gopal Oct 30 '16 at 17:49
  • 2
    Possible duplicate of [String escape into XML](http://stackoverflow.com/questions/1132494/string-escape-into-xml) – JLRishe Oct 30 '16 at 17:51
  • @JLRishe `InsertBreakTimeMessages="AAAAA" string xmlString = string.Format(clsGatway.InsertBreakTimeMessages, id) .Replace("[ENGMSG]", txtBoxCustomEngMsg.Text); ` I am simple adding text into Tag. Now issue & | < are not accepted. My method was to simply replace these characters on application end. – Nisar Afridi Oct 30 '16 at 18:02
  • @NisarAfridi You a real xml parser. Then you don't need to do thing manually.... I would use Linq2Xml for ex. `var elem = new XElement("sometag", "&<#"); var str = elem.ToString();` – L.B Oct 30 '16 at 18:11

3 Answers3

2

You shouldn't be trying to escape characters manually. There are libraries and methods that are already built to do this such the SecurityElement.Escape(). It specifically escapes invalid XML characters into a known safe format that can be unescaped later.

Soviut
  • 88,194
  • 49
  • 192
  • 260
  • That is one way to escape values in XML, but it sounds like OP is trying to build XML from strings by hand, which suggests they should be using whole different approach. – JLRishe Oct 30 '16 at 18:01
  • Then the OP has two problems :P – Soviut Oct 30 '16 at 18:03
  • @Soviut `SecurityElement.Escape()` dont have | sign. My thinking was to simple replace characters from string. I wanted to replace these all symbols : [link](https://www.dvteclipse.com/documentation/svlinter/How_to_use_special_characters_in_XML.3F.html#gsc.tab=0) – Nisar Afridi Oct 30 '16 at 18:18
  • 1
    @NisarAfridi Why do you want to escape `|` symbols? – JLRishe Oct 30 '16 at 18:22
  • @Soviut any special chracter user will enter it should not be escaped, it should show, anyway issue solved using above answer – Nisar Afridi Oct 30 '16 at 18:38
  • 1
    @NisarAfridi That's what unescaping is for. These tools exist for a reason and you're ignoring them in favour of a more fragile solution. – Soviut Oct 30 '16 at 20:09
  • @Soviut i understand that, but i was given this task, initially i made a regex to now allow special characters because in that message field there is no need of any special character, it is simple message field intended to display messages on KIOSK. – Nisar Afridi Oct 31 '16 at 05:51
  • Regardless, there are already tools you should be using to safely encode strings. Use those. – Soviut Oct 31 '16 at 14:32
0

I strongly advise using proper XML handling to build XML:

var id = 3;
var message = "&'<crazyMessage&&";

var xmlDoc = new XmlDocument();

using(var writer = xmlDoc.CreateNavigator().AppendChild())
{
    writer.WriteStartElement("ROOT");

    writer.WriteElementString("ID", id.ToString());

    writer.WriteStartElement("INPUT");
    writer.WriteElementString("ENGMSG", message);
    writer.WriteEndElement(); // INPUT

    writer.WriteEndElement(); // ROOT
}

var xmlString = xmlDoc.InnerXml;
Console.WriteLine(xmlString);

Ideone example

If you are using .NET 3.5 or higher, you can use Linq2Xml to build the XML, which is a bit cleaner:

var id = 3;
var message = "&'<crazyMessage&&";

var xml = new XElement("ROOT", 
    new XElement("ID", id),
    new XElement("INPUT", 
        new XElement("ENGMSG", message)
    )
);

var xmlString = xml.ToString();
Console.WriteLine(xmlString);
JLRishe
  • 99,490
  • 19
  • 131
  • 169
-3
public static string Transform(string input, Dictionary<string, string> replacements)
    {
        string finalString = string.Empty;
        for (int i = 0; i < input.Length; i++)
        {
            if (replacements.ContainsKey(input[i].ToString()))
            {
                finalString = finalString + replacements[input[i].ToString()];
            }
            else
            {
                finalString = finalString + input[i].ToString();
            }
        }

        return finalString;
    }
user1118759
  • 38
  • 1
  • 2
  • It would be better to use string builder in this case. – andyroschy Oct 30 '16 at 18:31
  • @NisarAfridi While this will succeed in replacing characters in the string, as I have already pointed out, this is the **wrong** way to solve your problem. The question you asked is an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – JLRishe Oct 31 '16 at 03:47
  • Yes maybe i didn't clarify question, but in my question i clearly asked about replacing those characters with their equivalent codes. It was very very late so maybe it became XY Problem. :P. Anyway thanks for your responses. – Nisar Afridi Oct 31 '16 at 05:57