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?
source to share
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.
source to share
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.
source to share