使用c#查找并替换XML文件中的文本

时间:2021-06-07 16:50:58

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.

我正在尝试使用c#查找并替换xml文件中的文本。我想要的是在整个文件的url链接中更改服务器名。

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?

我试着使用System.xml。linq (XDocument.load(xmlpath))),但它只是将整个xml文件作为一行字符串提供给我。有什么办法可以替换文本吗?注意url不在特定的节点中。,它们在整个文件中都是随机的。我可以手动完成文件的查找和替换,有没有一种编程方式?

1 个解决方案

#1


5  

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

如果您将整个xml文件作为字符串,您可以通过以下操作替换所需的内容:

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:

但是通常如果你想要改变一个xml标签的值,我可以给你一个例子,你可以把它放在你的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");

#1


5  

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

如果您将整个xml文件作为字符串,您可以通过以下操作替换所需的内容:

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:

但是通常如果你想要改变一个xml标签的值,我可以给你一个例子,你可以把它放在你的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");