如何用XDT变换替换字符串

时间:2017-06-13 18:06:30

标签: c# xml visual-studio xdt-transform

我想要转换的配置看起来像这样:

<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>

我想做的就是用D:\my\old\path\<unique value>

替换D:\my\new\path\<unique value>

我只看到示例替换&lt;&gt;&lt;&gt;之间的完整值或者&lt;&gt;内的财产。我只想在文件中的每个地方做一个简单的字符串替换吗?

1 个答案:

答案 0 :(得分:-1)

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

        }
    }
}