Replacing backslashes in C#

Hello all. What I am doing here is calling a a stored procedure (sproc) from C#, which is returning me a result set in xml format. The xml looks like this:

<row Type=\"Revenue\" Product=\"Payday\" Frequency=\"Today\" Value=\"1.500\" Teller=\"\" Location=\"1\"/>

But it should look like this:
<row Type="Revenue" Product="Payday" Frequency="Today" Value="1.500" Teller="" Location="1"/>

I am not sure where the \'s are coming from, looks like it might have to do with having quotes in my xml coming back and c# rendering it as an illegal escape sequence.. My sql does not have any \'s in them. I have a feeling that C# is treating this xml that gets returned by using my (XML Reader Object).ReadOuterXml(); . What am I doing wrong here folks. Please let me know. Thanks

Who is Participating?
danielsonchrisConnect With a Mentor Commented:
Awesome man.. now we can see the situation.
[0xa]     0x22 '"'     char
     [0xb]     0x52 'R'     char
     [0xc]     0x65 'e'     char
     [0xd]     0x76 'v'     char
     [0xe]     0x65 'e'     char
     [0xf]     0x6e 'n'     char
     [0x10]     0x75 'u'     char
     [0x11]     0x65 'e'     char
     [0x12]     0x22 '"'     char

The good news is that string is perfectly formed!  The bad news is that still doesn't solve why the XML parser is failing.  I think we need to see how the sRetXML looks.  Can you paste the entire XML string.  Beginning with:
<?xml version="1.0" encoding="UTF-8"?>

Where are you see this?  Try outputting your result set to the Console and see if it looks correct.  If you are seeing this in the debugger, that is just the way that Visual Studio represents strings, and everything should be okay.
slimbxAuthor Commented:
Here is my code to help:  (EXCUSE THE LACK INDENTATIONS)

private string GetXML(string sCmnd, string sParamList, SqlConnection oConn,ref string sErrMsg)
//The purpose of this function is to return xml data in a single node with attributes based on command passed in
string sRetXML = "";
string sStartDate = "";
string sEndDate = "";
clsUtility cUtil = new clsUtility();                  //instantiate clsUtility class for use

//parse out the data parameter line passed in
char[] sep = {','};
string[] sParams = sParamList.Split(sep);
//determine the start and end dates prior to execution based on frequency, based on specified date
sStartDate = cUtil.GetStartDate(sParams[4].Trim(),sParams[5].Trim());
sEndDate = cUtil.GetEndDate(sParams[4].Trim(),sStartDate);
//begin building the command object to execute selected sproc
SqlCommand sqlCmnd = new SqlCommand(sParams[0].Trim(),oConn);
sqlCmnd.CommandType = CommandType.StoredProcedure;
//XmlReader oReader = null;
SqlDataReader oReader = null;
//perform call to correct stored procedure
      //build a command object based on stored procedure to query to retrieve xml
      sqlCmnd.Parameters.Add(new SqlParameter("@pQueryType",SqlDbType.VarChar,3));
      sqlCmnd.Parameters["@pQueryType"].Value = sParams[1];
      sqlCmnd.Parameters.Add(new SqlParameter("@pType",SqlDbType.VarChar,25));
      sqlCmnd.Parameters["@pType"].Value = sParams[2];
      sqlCmnd.Parameters.Add(new SqlParameter("@pProduct",SqlDbType.VarChar,15));
      sqlCmnd.Parameters["@pProduct"].Value = sParams[3];
      sqlCmnd.Parameters.Add(new SqlParameter("@pFrequency",SqlDbType.VarChar,5));
      sqlCmnd.Parameters["@pFrequency"].Value = sParams[4];
      sqlCmnd.Parameters.Add(new SqlParameter("@pStartDate",SqlDbType.SmallDateTime,0));
      sqlCmnd.Parameters["@pStartDate"].Value = sStartDate;
      sqlCmnd.Parameters.Add(new SqlParameter("@pEndDate",SqlDbType.SmallDateTime,0));
      sqlCmnd.Parameters["@pEndDate"].Value = sEndDate;
      sqlCmnd.Parameters.Add(new SqlParameter("@pTeller",SqlDbType.VarChar,3));
      sqlCmnd.Parameters["@pTeller"].Value = sParams[6];
      sqlCmnd.Parameters.Add(new SqlParameter("@pLocation",SqlDbType.Int,0));
      sqlCmnd.Parameters["@pLocation"].Value = sParams[7];
               //oReader = sqlCmnd.ExecuteXmlReader();                  
      oReader = sqlCmnd.ExecuteReader();
      //determine if data reader returned an xml string or not
      if (oReader.Read())
            //sRetXML = oReader.ReadOuterXml();
            sRetXML = oReader.GetString(0);
            //sRetXML = sRetXML.Replace("\\" & Chr(&H22),Chr(&H22));
      catch (Exception e)
      sErrMsg = "Exception " + e.Source + " was thrown because " + e.Message + "\n";
      sRetXML = "";                        //errors raised, return blank string, no xml found      }
      return sRetXML;

So when I set sRetXML, it comes back as the following xml :
<row Type=\"Revenue\" Product=\"Payday\" Frequency=\"Today\" Value=\"1.500\" Teller=\"\" Location=\"1\"/>

ANd this then is being added to an XmlDocument object, when later on I am transforming with xsl which gives me errors due to the structure of the xml.
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

Well the quick way around is...
sRetXML = oReader.GetString(0);
sRetXML = sRetXML.Replace( "\\"", "\"" );

This isn't getting to the core of the problem, but is a quick solution around it.
slimbxAuthor Commented:

Trying your suggestion did not remove the escape sequences. I tried that one this morning, and its almost as if C# does not allow the escape characters to be picked up. Odd
THis is rather interesting.. crack open the debugger and give us a snippit of the hexadecimal values you are seeing in the string.  

Particularly.. translate this for us..

Ordinarily this would be only 4 bytes, but you may see 8 bytes.  0x00 buffered. Basically we are all insterested in known if you are getting some UTF-16 translation from the SQL Server or in your C#.  If this is the case then you will need to take that into account prior to Replacing the string.

slimbxAuthor Commented:
It is showing up like this in the debugger:

<row Type="Revenue" Product="Payday" Frequency="Today" Value="7457.5000" Teller="" Location="1.400000000000000e+001"/>

Which looks normal. But when I save that sucker to my string var, I get the xml that has slashes everywhere. I think I understand what you said earlier danielsonchris, but can you explain it in c# for beginners terms, being that is kind of where I am, and also what I can do to get this xml spitting out like it does in the debugger into my string. Thanks!!!

sorry about that.. do something like the following only for debugging purposes.

sRetXML = oReader.GetString(0);
char[] chr_array_data = sRetXML.toCharArray();

Set a break point somewhere after the chr_array_data has been filled.  Right click in the variable watch window and select "Hexadecimal Display".  From there you will be able to see the true nature of the beast.

slimbxAuthor Commented:
This is what comes back:

"<row Type=\"Revenue\" Product=\"Payday\" Frequency=\"Today\" Value=\"7457.5000\" Teller=\"\" Location=\"14\"/>"

as the value of my variable sRetXML. I think this is what you want.
slimbxAuthor Commented:
FYI: This is the hexidecimal display watch value
Well not really, what I was wanting is the actual hexadecimal representation of the bytes.  (thus I had you create a char array above)

Here is a nasty massage technique that will massage to ASCII.

using System.Text;

ASCIIEncoding ascii = new ASCIIEncoding();
ascii.GetBytes( stringVal );
byte[] bt = ascii.GetBytes( sRetXML );
sRetXML = Encoding.ASCII.GetString( bt );

//At this point now try the replace...
sRetXML = sRetXML.Replace( "\\"", "\"" );

//Let's see if this works for you.
slimbx, are you getting the value of sRetXML from a watch while the code is running?  I am asking as the only time that I see the " being escaped is when I am looking at the string in a watch. So, what does the string look like when you output it to the console or a file?  Or is this what you are doing?
ingore the
ascii.GetBytes( stringVal );
line from the post above.
slimbx had claimed that the XML Parser was choking on it.
That brings up a good point though.  What is the error code and string of XML that the parser is choking on?  Don't copy and paste from the debugger for this one.  Copy and paste from a console window.

Console.Write( sRetXML );
It might be choking for another reason...  As I stated the only time that I have seen the quites being escaped is when I get the string through a watch or some other means while debugging.
slimbxAuthor Commented:

I tried the code and it didn't catch. My string variable still gets populated with the bad xml text I specified above.



When I display the xml to a file or variable, it spits out as:
<row Type=\"Revenue\" Product=\"Payday\" Frequency=\"Today\" Value=\"1.500\" Teller=\"\" Location=\"1\"/>

When I display in the debug window it spits out as:
<row Type="Revenue" Product="Payday" Frequency="Today" Value="7457.5000" Teller="" Location="14"/>

Hmmm.... Then danielsonchris' code should have worked... I guess you could try a regex...

using System.Text.RegularExpressions;

Regex regex = new Regex(
    | RegexOptions.Multiline
    | RegexOptions.IgnorePatternWhitespace
    | RegexOptions.Compiled

then you would simply do

regex.Replace( sRetXML, "" );
Sorry, the last line of the comment should read:

string sRet = regex.Replace( sRetXML, "" );
slimbxAuthor Commented:

I pasted and used your code as well, the end result of the string continues to be:
<row Type=\"Revenue\" Product=\"Payday\" Frequency=\"Today\" Value=\"1.500\" Teller=\"\" Location=\"1\"/>

I guess the coding jinx is in town. For friendly competition, I have rasied the stakes. Please keep the ideas coming.

I still think you need to do two things.

1)  Break the string into a character array
sRetXML = oReader.GetString(0);
char[] chr_array_data = sRetXML.toCharArray();
//NOW loook at the character array through a debugger using "Hexadecimal Display" and a nice chunk of the bytes here.

2)  Look into why the XML Parser is choking on the string.  What is the Exception string returned?  Also please paste the entire XML string here.

Is that the content of sRet or sRetXML?  The string without the \ will be in sRet...
slimbxAuthor Commented:
Sorry for the retardedness...Its Friday!

-      chr_array_data      {Length=0x62}      char[]
      [0x0]      0x3c '<'      char
      [0x1]      0x72 'r'      char
      [0x2]      0x6f 'o'      char
      [0x3]      0x77 'w'      char
      [0x4]      0x20 ' '      char
      [0x5]      0x54 'T'      char
      [0x6]      0x79 'y'      char
      [0x7]      0x70 'p'      char
      [0x8]      0x65 'e'      char
      [0x9]      0x3d '='      char
      [0xa]      0x22 '"'      char
      [0xb]      0x52 'R'      char
      [0xc]      0x65 'e'      char
      [0xd]      0x76 'v'      char
      [0xe]      0x65 'e'      char
      [0xf]      0x6e 'n'      char
      [0x10]      0x75 'u'      char
      [0x11]      0x65 'e'      char
      [0x12]      0x22 '"'      char
      [0x13]      0x20 ' '      char
      [0x14]      0x50 'P'      char
      [0x15]      0x72 'r'      char
      [0x16]      0x6f 'o'      char
      [0x17]      0x64 'd'      char
      [0x18]      0x75 'u'      char
      [0x19]      0x63 'c'      char
      [0x1a]      0x74 't'      char
      [0x1b]      0x3d '='      char
      [0x1c]      0x22 '"'      char
      [0x1d]      0x50 'P'      char
      [0x1e]      0x61 'a'      char
      [0x1f]      0x79 'y'      char
      [0x20]      0x64 'd'      char
      [0x21]      0x61 'a'      char
      [0x22]      0x79 'y'      char
      [0x23]      0x22 '"'      char
      [0x24]      0x20 ' '      char
      [0x25]      0x46 'F'      char
      [0x26]      0x72 'r'      char
      [0x27]      0x65 'e'      char
      [0x28]      0x71 'q'      char
      [0x29]      0x75 'u'      char
      [0x2a]      0x65 'e'      char
      [0x2b]      0x6e 'n'      char
      [0x2c]      0x63 'c'      char
      [0x2d]      0x79 'y'      char
      [0x2e]      0x3d '='      char
      [0x2f]      0x22 '"'      char
      [0x30]      0x54 'T'      char
      [0x31]      0x6f 'o'      char
      [0x32]      0x64 'd'      char
      [0x33]      0x61 'a'      char
      [0x34]      0x79 'y'      char
      [0x35]      0x22 '"'      char
      [0x36]      0x20 ' '      char
      [0x37]      0x56 'V'      char
      [0x38]      0x61 'a'      char
      [0x39]      0x6c 'l'      char
      [0x3a]      0x75 'u'      char
      [0x3b]      0x65 'e'      char
      [0x3c]      0x3d '='      char
      [0x3d]      0x22 '"'      char
      [0x3e]      0x37 '7'      char
      [0x3f]      0x34 '4'      char
      [0x40]      0x35 '5'      char
      [0x41]      0x37 '7'      char
      [0x42]      0x2e '.'      char
      [0x43]      0x35 '5'      char
      [0x44]      0x30 '0'      char
      [0x45]      0x30 '0'      char
      [0x46]      0x30 '0'      char
      [0x47]      0x22 '"'      char
      [0x48]      0x20 ' '      char
      [0x49]      0x54 'T'      char
      [0x4a]      0x65 'e'      char
      [0x4b]      0x6c 'l'      char
      [0x4c]      0x6c 'l'      char
      [0x4d]      0x65 'e'      char
      [0x4e]      0x72 'r'      char
      [0x4f]      0x3d '='      char
      [0x50]      0x22 '"'      char
      [0x51]      0x22 '"'      char
      [0x52]      0x20 ' '      char
      [0x53]      0x4c 'L'      char
      [0x54]      0x6f 'o'      char
      [0x55]      0x63 'c'      char
      [0x56]      0x61 'a'      char
      [0x57]      0x74 't'      char
      [0x58]      0x69 'i'      char
      [0x59]      0x6f 'o'      char
      [0x5a]      0x6e 'n'      char
      [0x5b]      0x3d '='      char
      [0x5c]      0x22 '"'      char
      [0x5d]      0x31 '1'      char
      [0x5e]      0x34 '4'      char
      [0x5f]      0x22 '"'      char
      [0x60]      0x2f '/'      char
      [0x61]      0x3e '>'      char



The content returned back that way in the sRet variable.


slimbxAuthor Commented:

The xml looks malformed in c#, but I let the app run, the way it is rendered is accurate to represent the escape sequences for that particular string. When I spit all of my xml values into an xml file and save it to the dom, all is well formed. I think that what I was assuming was the display of xml would be like what I am use to and it was not via c#. Thanks a million.



I feel bad because you were helping me as well. Want me to open a dummy question so you can accept for some points? Let me know.

No, not at all... Glad you were able to figure it out...
Wasn't that what I said in the beginning? ...
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.