【问题标题】:How can I replace a string with XDT transforms如何用 XDT 转换替换字符串
【发布时间】:2023-03-17 16:59:01
【问题描述】:

我要转换的配置如下所示:

<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\new\path\&lt;unique value&gt;替换D:\my\old\path\&lt;unique value&gt;

我只看到过替换 之间的完整值或 中的属性的示例。我只想在文件中的任何地方做一个简单的字符串替换这可能吗?

【问题讨论】:

  • 可以替换所有属性,但不能使用xdt替换所有值,see。例如&lt;mypath xdt:Transform="SetAttributes" xdt:Locator="XPath(//blah/*)" path="D:\h" /&gt; 使用 XPath 替换 mypath 元素中的所有路径属性。不幸的是,您不能替换属性的一部分。 XSLT 转换可以替换所有元素值,但我不确定它是否可以替换字符串的一部分。

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


【解决方案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"));
            }

        }
    }
}

【讨论】:

  • 我不想以编程方式执行此操作。对于 XDT 转换可以做的所有疯狂的事情,它们必须能够进行简单的字符串替换。
  • 代替XLinq,它可以立即使用具有新元素值的xdt变换......
猜你喜欢
  • 2016-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多