Link to home
Start Free TrialLog in
Avatar of KnightWhoSaysNi
KnightWhoSaysNiFlag for United States of America

asked on

Search And Replace Text in XML File with C#

I would like to search and replace text in an xml file and save a new version of that file.

So, I have an xml file called SS.xml and would like to replace "geltimer1" with "geltimer2" at all levels / nodes and save the file out to SS2.xml.

I have several strings to replace in each file and several files to process, otherwise I would just use Notepad++.

Thanks in Advance
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Please post a sample of the XML file. XML files are case sensitive as well as it has a hierarchy which must be considered.
Avatar of KnightWhoSaysNi

ASKER

XML file attached.
ss.xml
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Works well.  I just had to setup local variables for the strings.

{
        String InputPath = @"C:\Users\Philip\Desktop\ss.xml";
        String OutputPath = @"C:\Users\Philip\Desktop\Output\ss2.xml";

        // Load the XML document into memory from the file system. Change File Path to yours
        XDocument xdoc = XDocument.Load(InputPath);

        // Query the XML document for the string "GELTIMER!" and return it as part of the result set
        List<XElement> nodes = (from node in xdoc.Descendants("Property")
                                where node.Attributes("name").Any(n => n.Value != "CONFIGURED_ITEMS") && node.Value.Contains("QAL_SS_GELTMR1")
                                select node).ToList();

        // Replace all values of GELTIMER1 with GELTIMER2
        nodes.ForEach(n => n.Value = n.Value.Replace("QAL_SS_GELTMR1", "QAL_SS_GELTMR2"));

        // Save the xml as SS2.xml
        xdoc.Save(OutputPath);
        }

Open in new window