Find and replace text in XML file using C #

I am trying to find and replace text in an XML file using C #. I want to change the server name in the url throughout the file.

http://Server1.extranet.abc/server1webdev/rest/services/ABC/ABC_Base/MapServer 

to

 http://Server2.extranet.abc/server1webdev/rest/services/ABC/ABC_Base/MapServer 

I tried using System.xml.linq (XDocument.load (xmlpath)) but it just gives me the whole XML file as one line of a line. Is there any way to replace the text? Please note that the URL is not located in specific sites. They are random throughout the file. I can do this manually by searching and replacing the file, is there any way to do this programmatically?

+6
source share
1 answer

if you have the whole xml file as a string, you can replace what you need:

 string oldStr = @"http://Server1.extranet.abc/server1webdev/rest/services/ABC/ABC_Base/MapServer"; string newStr = @"http://Server2.extranet.abc/server1webdev/rest/services/ABC/ABC_Base/MapServer "; doc.Replace(oldStr, newStr); 

but usually, if you want to change the tag value in xml, I can offer an example, and you put it in your xml:

  XDocument doc = XDocument.Load("D:\\tst.xml"); foreach (XElement cell in doc.Element("Actions").Elements("Action")) { if (cell.Element("ActionDate").Value == oldStr) { cell.Element("ActionDate").Value = newStr; } } doc.Save("D:\\tst.xml"); 
+5
source

Source: https://habr.com/ru/post/953638/


All Articles