使用标记查找参数(IndexOf或IndexOfAny)

时间:2011-10-24 20:23:23

标签: c# xml xpath indexing token

目前,我能够在我提供的令牌中获得xpath的值,如下所示

using (StreamReader streamReader = new StreamReader(memoryStream))
{
    while ((CurrentLine = streamReader.ReadLine()) != null)
    {
        int startPos = CurrentLine.IndexOf("{:");
       int endPos = CurrentLine.LastIndexOf(":}");

       if (startPos > 0 && endPos > 0)
       {
           string xPathstr = CurrentLine.Substring(startPos + 2, (endPos - startPos - 2));

           XPathNodeIterator myXPathNodeIterator = myXPathNavigator.Select("/"+ xPathstr);

           while (myXPathNodeIterator.MoveNext())
           {
               Console.WriteLine(myXPathNodeIterator.Current.Value);
               TemplateMemoryBuilder.Append(CurrentLine.Replace(CurrentLine.Substring(startPos, ((endPos + 2) - startPos)), myXPathNodeIterator.Current.Value));
               TemplateMemoryBuilder.Append(Environment.NewLine);
           }

       }
       else
       {
           TemplateMemoryBuilder.Append(CurrentLine);
           TemplateMemoryBuilder.Append(Environment.NewLine);
       }
    }
}

如果在一行中找到多个标签,我试图找到一种方法来获取带有标签的参数,例如:

This is a test to merge item {:/MyTest/TestTwo/Text1:} and {:/MyTest/TestTwo/Text2:} on the same line.

我可以使用IndexOfAny方法完成此任务吗?我不知道该怎么做。程序工作正常,直到我发现这是给我的测试可能的结果

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式来匹配您的令牌。这将使您的代码更具可读性。

示例正则表达式和匹配代码

        var regex = new Regex("{:.+?}");
        var input =
            "This is a test to merge item {:/MyTest/TestTwo/Text1:} and {:/MyTest/TestTwo/Text2:} on the same line.";
        var matches = regex.Matches(input);

找到两个没有索引操作和(代价高昂的)字符串操作的匹配项。