Search code examples
c#.net

Simple string replace in xml


I have a string that contains a fair bit of XML, it's actually xml that describes a word document(document.xml). I want to simply replace a part of the string with an empty string effectivally removing it from the string. This sounds straight forward but I'm not getting the result I expect.

Here is what some of the XML looks like, this is just the first 10 lines:

<w:body xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
    <w:p w:rsidR="00CB3A3E" w:rsidP="00257CF7" w:rsidRDefault="008C1E91">
        <w:pPr>
            <w:pStyle w:val="Heading-Title" />
        </w:pPr>
        <w:r>
            <w:t>References</w:t>
        </w:r>
    </w:p>
    <w:sdt> 

As I said this is in a string. I simply try to replace <w:t>References</w:t> with an empty string. I am doing it like so:

//xmlBody is the string that is holding the xml
xmlBody.Replace("<w:t>References</w:t>", " ");

This is not working, the string is unaltered when I do this. What am I doing wrong? Any advice would be appreciated, thanks much!


Solution

  • xmlBody = xmlBody.Replace("<w:t>References</w:t>", "");
    

    The Replace function doesn't change the source string; it returns a new string with the changes made. In fact, C# strings cannot be changed. If you check out the documentation, it says that they're immutable.