Share via


string.Replace on special characters ("\

Question

Monday, September 21, 2009 8:44 AM

i have a string which i need to convert to an XML document. but the string is being returned with special characters for the quotes.

e.g. <?xml version=\1.0\ encoding=\utf-8\?>

so when i try to load the string into an XMLDocument i get illegal characters in path but how do i go about replacing the \ with just "

Cheers.

All replies (12)

Monday, September 21, 2009 12:38 PM âś…Answered

The exception has nothing to do with XML.  It says that the filename contains illegal characters.  That would indeed happen if the name contains double quotes.  Pick a better name, don't confuse the content of an XML document with the name of the file that contains it.
Hans Passant.


Monday, September 21, 2009 9:54 AM

Hi Craig,

I found this article or whatever you want to call it rather useful http://msdn.microsoft.com/en-us/library/362314fe%28VS.71%29.aspx

Also what you could do is write the hex/unicodevalue for the \ character which is \u005c in the String.Replace function here is an example. The " char is \u0022

String foo = "mo\"o";

foo = foo.Replace("\u005c\u0022", "\u0022");

Console.WriteLine(foo);

The output will be:

mo"o

Hope this helps.

Cheers!


Close but no cigar


Monday, September 21, 2009 10:02 AM

Why not just do:

string s = ...

s = s.Replace("\\", "\");


Monday, September 21, 2009 10:42 AM

I think he wanted to remove the \ in the xml output <?xml version=\ "1.0**\** " encoding=\ "utf- 8**\** "?> and the s = s.Replace("\\", "\"); generates the following errors

Unexpected character '\ (at the "\ "" position)
Invalid expression term ' " ' (same position as line above)

The list continues with a few more errors but I think you get the point :)

Cheers!
Close but no cigar


Monday, September 21, 2009 10:45 AM

I don't see where he says he tried that...

And more to the point, why use the unicode code \u0022 when you can just use \  ?


Monday, September 21, 2009 10:58 AM

He didn't try it I did and got those errors when compiling. I also tried writing the output to a label in a windows forms project and the text just disappears when using the \ as the last parameter, instead of leaving white spaces or actually replacing the \ with ".

Have you tried compiling your code? I don't think the compiler is to fund of the \ notation in a " <string> " thus making sure the compiler knows which char to replace and with what (if being special chars).

I don't know if it is different in older versions of VS than the 2008 one or in any other programming language but I'm using VS2008 (.NET SP1) and the language I'm testing it in is C#

Close but no cigar


Monday, September 21, 2009 11:39 AM

Yes, this works fine (note that you can't use the header line alone, you must have at least one other element):
(I'm also using VS2008).

What code are you using?

using System;
using System.Xml;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>";
            Console.WriteLine("Converting: " + s);
            s = s.Replace("\\\"", "\"");
            Console.WriteLine("Converted: " + s);

            // Add some XML to prevent the "root element is missing" exception:

            s += "<DUMMY></DUMMY>";

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(s);
        }
    }
}

Monday, September 21, 2009 2:10 PM

If one wanted to write to an XML file I would instead use the System.Xml class and start the document off with XmlTextWriter xtw = new XmlTextWriter(FileName, Encoding.UTF8); and then use the xtw.WriteStartDocument(); which will automatically write the <?xml version="1.0" encoding="utf-8"?> in the newly created xml file without any hassle. But if one had a function that return a string containing \ and wanted to replace it with just " I would do as I wrote in my first example since it seems to be working in any case when special chars are involved.

Why it didn't work for me the first time might be with something in the windows forms project not liking the \\ statement inside the " " nor the "\", below is the code I used which gives the errors on the Replace() line.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Temp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnTemp_Click(object sender, EventArgs e)
        {
            String myStr = "<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>";

            myStr = myStr.Replace("\\\", "\""); //<-- getting those errors I wrote in previous post

            lblTemp.Text = myStr;
        }
    }
}

The error with illegal characters in path sounds as nobugz said like there is a problem with the file/pathname rather than with the line of XML posted. But then if you have something that returns the xml code in that way I should either try Matthews approach or mine or combine them if you like.
Close but no cigar


Monday, September 21, 2009 2:15 PM

The reason it didn't work for you is because you got the string replacement wrong.

If you look at my first reply, I said do this:

s = s.Replace("\\", "\");

But you did this:

myStr = myStr.Replace("\\, "\");

Yours is missing a quote, so it won't even compile.


Monday, September 21, 2009 3:45 PM

response = response.Replace(

"\\","\");
or
response = response.Replace("\u005c\u0022", "\u0022");

would not remove the \ from the string, the string is what is being returned from an HttpWebRequest to an Axis/Apache webservice so there is no filename or paths involved in reading the response (but your where along the right lines nobugz!)

the problem was all MY FAULT had bit of monday morning blues:-

 

XmlDocument xhtmlDoc = new XmlDocument();
xhtmlDoc.Load(response);

spot the glaring error.....Load....LoadXML may have been a better choice!!


Friday, October 23, 2009 8:56 AM

Hello Craig,

I think I understand your question, because I also have the same issue, I think you use below methods to convert your string to xml:

XmlDocument doc=new XmlDocument();

doc.Load(yourstring);

Please remember this is not correct, becasue the XmlDocument.Load method is expecting a file name or a URL. So if

you want to load the XML from a string, you need to use the XmlDocument.LoadXml method.

Please let me know whether it could helps.

Thanks,


Friday, October 23, 2009 9:04 AM

Craig already said he was using Load() by mistake, and that he should have been using LoadXml(). Look at his last post immediately above yours...