SSIS C# 脚本任务:如何在大型 XML 文件上使用增量匹配/替换模式



还有其他类似的问题被提出和回答,但这些答案都不适用于我正在尝试做的事情,或者没有足够的信息让我知道如何在我自己的代码中实现它。我已经做了两天了,现在必须寻求帮助。

我在 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++;
}
}
}

您使用Replace方法走在正确的道路上,但在递增时需要使用MatchEvaluater参数。

string inputFile = Dts.Variables["User::xmlFilename"].Value.ToString();
string outPutfile = Dts.Variables["User::xmlOutputFile"].Value.ToString();
string fileText = File.ReadAllText(inputFile);
//get any number between elements
Regex reg = new Regex("<ns1:recordIdentifier>[0-9]</ns1:recordIdentifier>");
string xmlStartTag = "<ns1:recordIdentifier>";
string xmlEndTag = "</ns1:recordIdentifier>";
//assuming this starts at 1
int incrementInt = 1;
fileText = reg.Replace(fileText, tag =>
{ return xmlStartTag + incrementInt++.ToString() + xmlEndTag; });
File.WriteAllText(outPutfile, fileText);

最新更新