【发布时间】:2018-10-24 21:58:11
【问题描述】:
已经提出并回答了其他类似的问题,但这些答案都不适用于我正在尝试做的事情,或者没有足够的信息让我知道如何在我自己的代码中实现它。我已经用了两天了,现在必须寻求帮助。
我在 SSIS 包中有一个脚本任务,我需要在其中对包含数千个记录标识符标记的大型 XML 文件进行匹配和替换。每一个都包含一个数字。我需要这些数字是连续的并加一。例如,在 xml 文件中,我可以找到如下所示的标签:
<ns1:recordIdentifier>1</ns1:recordIdentifier>
<ns1:recordIdentifier>6</ns1:recordIdentifier>
<ns1:recordIdentifier>223</ns1:recordIdentifier>
<ns1:recordIdentifier>4102</ns1:recordIdentifier>
我需要找到并用连续增量替换这些标签,如下所示:
<ns1:recordIdentifier>1</ns1:recordIdentifier>
<ns1:recordIdentifier>2</ns1:recordIdentifier>
<ns1:recordIdentifier>3</ns1:recordIdentifier>
<ns1:recordIdentifier>4</ns1:recordIdentifier>
到目前为止,我的代码导致所有数字均为“1”且没有增量。
我尝试了几十种不同的方法,但都没有奏效。
关于如何修改以下代码以根据需要递增的任何想法?
public void Main()
{
string varStart = "<ns1:recordIdentifier>";
string varEnd = "</ns1:recordIdentifier>";
int i = 1;
string path = Dts.Variables["User::xmlFilename"].Value.ToString();
string outPath = Dts.Variables["User::xmlOutputFile"].Value.ToString();
string ptrn = @"<ns1:recordIdentifier>\d{1,4}<\/ns1:recordIdentifier>";
string replace = varStart + i + varEnd;
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null && i>0)
{
File.WriteAllText(outPath, Regex.Replace(File.ReadAllText(path),
ptrn, replace));
i++;
}
}
}
【问题讨论】:
标签: c# regex pattern-matching increment script-task