Search code examples
c#xmlvisual-studioxdt-transform

How can I replace a string with XDT transforms


My config I want to transform looks like this:

<sdfsdfsd>

<blah>
<mypath>D:\my\old\path\aaa</mypath>
</blah>

<blah>
<mypath>D:\my\old\path\bbb</mypath>
</blah>

<blah>
<mypath>D:\my\old\path\ccc</mypath>
</blah>

</sdfsdfsd>

All I want to do is replace D:\my\old\path\<unique value> with D:\my\new\path\<unique value>

I have only seen examples replaces a complete value between <><> or a property inside <>. I just want to do a simple string replace everywhere in the file is this possible?


Solution

  • Try xml linq

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string xml = 
                    "<sdfsdfsd>" +
                        "<blah>" +
                        "<mypath>D:\\my\\old\\path\\aaa</mypath>" +
                        "</blah>" +
                        "<blah>" +
                        "<mypath>D:\\my\\old\\path\\bbb</mypath>" +
                        "</blah>" +
                        "<blah>" +
                        "<mypath>D:\\my\\old\\path\\ccc</mypath>" +
                        "</blah>" +
                    "</sdfsdfsd>";
    
                XElement element = XElement.Parse(xml);
    
                foreach(XElement mypath in  element.Descendants("mypath"))
                {
                    mypath.SetValue(((string)mypath).Replace("old","new"));
                }
    
            }
        }
    }