GBh
GBh

Reputation: 343

Find and Replace text in XML file using c#

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?

Upvotes: 7

Views: 39240

Answers (3)

Denise Skidmore
Denise Skidmore

Reputation: 2416

List<XElement> allElements = xmlDocument.Descendants().ToList();
foreach (XElement element in allElements.Where(e => e.Value == oldstring))
{
    element.Value = newstring
}

Alternatively Where clause could have a Contains and Value could use string replace.

A side tip to preserve line numbers when loading XDocument, which is super handy if you're doing validation:

XDocument xmlDocument = XDocument.Load(xmlFile, LoadOptions.SetLineInfo);

Upvotes: 1

testalino
testalino

Reputation: 5678

Using XDocument there is currently no built-in way to replace text in the whole file. However what you can do is

XDocument document = XDocument.LoadFrom(path);
var docText = document.ToString().Replace(urlA, urlB);
using (var reader = new StringReader(docText))
    document = XDocument.Load(reader, LoadOptions.None);

Which is not ideal, but at least it's a workaround.

Upvotes: 0

No Idea For Name
No Idea For Name

Reputation: 11597

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");

Upvotes: 10

Related Questions