【问题标题】:SSIS C# Script Task: How to match/replace pattern with increment on a large XML fileSSIS C# 脚本任务:如何在大型 XML 文件中使用增量匹配/替换模式
【发布时间】: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


    【解决方案1】:

    您使用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);
    

    【讨论】:

    • 谢谢userfl89!你帮我解决了我的问题。唯一的问题是模式匹配不起作用。我有从 1 t0 4000 开始查找和替换的数字,但您提供的数字只能找到个位数。当我重新插入 @"\d{1,4}\/ns1:recordIdentifier>" 的原始模式时,一切正常。
    • 很高兴它对你有用。抱歉,我发布的内容是作为一个通用示例,我可能应该更清楚地说明这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 2018-05-13
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多