Find and Replace text in XML file using c#

十年热恋 提交于 2020-01-14 09:04:12

问题


I am trying to find and replace text in an xml file using c#. What I want is to change server name in the url link 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 simply gives me the whole xml file as one line of string. Is there a way I can replace the text?Note that the url's are not in specific nodes., they are random throughout file. I am able to do this manually through the file's find and replace, is there a way of doing this programmatically?


回答1:


if you have the entire xml file as string you can replace what you need by doing:

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 normally if you want to change a value of a tag in xml i can suggest an example and you put it to use 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");


来源:https://stackoverflow.com/questions/18744660/find-and-replace-text-in-xml-file-using-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!