KnightWhoSaysNi
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
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
Please post a sample of the XML file. XML files are case sensitive as well as it has a hierarchy which must be considered.
ASKER
XML file attached.
ss.xml
ss.xml
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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);
}