C # string replacement, doesn't work

I have a line that I was reading into:

TextReader tr = new StreamReader(this.dataPath );
string contents = tr.ReadToEnd(); 

      

Content value starts with:

"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n....."

      

When I try to execute

        string styleSheet = "<?xml-stylesheet type=\"text/xsl\" href=\"message.xsl\"?>";
        string xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
        TextReader tr = new StreamReader(this.dataPath );
        string contents = tr.ReadToEnd(); 
        contents.Replace(xmlString,xmlString + styleSheet );

      

Will absolutely not detect the first occurrence of the XmlString. Any ideas why?

+2


source to share


6 answers


Try

contents = contents.Replace(xmlString,xmlString + styleSheet );

      



This is because the String class is immutable.

+27


source


The Replace () method returns a new string object, so you'll have to change your code to:



 content = contents.Replace(xmlString,xmlString + styleSheet );

      

+5


source


you probably want to do this:

string styleSheet = "<?xml-stylesheet type=\"text/xsl\" href=\"message.xsl\"?>";
string xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
TextReader tr = new StreamReader(this.dataPath );
string contents = tr.ReadToEnd(); 
string result = contents.Replace(xmlString,xmlString + styleSheet );

      

Currently, you are not committing the substitution results you do on the last line.

+3


source


System.String

is immutable. Operations such as Replace

return a new row rather than modifying the row this

. Use System.Text.StringBuilder

if you really need a mutable string, or just assign the result of the call to a Replace

variable.

+2


source


To get technical (and who doesn't like it) if you are looking for the line `

<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n.....

      

The search string should be

"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>\\r\\n"

      

or

 @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"

      

+1


source


This doesn't really answer your question, but this has been answered many times already, so please allow me to postpone this.

I've seen many cases where people read the content of a stream into a string so that some very simple manipulations can be done. In many cases, and of course in this case, the operation can be performed without making a copy of the entire string and working on it.

With less effort than your existing code, you can write a StreamStringReplace method that takes an input stream, an output stream, a search string, and a replacement string as parameters. This would be much more efficient, especially if your xml documents can get massive.

+1


source







All Articles