Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用字典将文本替换为字符串_C#_String Parsing - Fatal编程技术网

C# 使用字典将文本替换为字符串

C# 使用字典将文本替换为字符串,c#,string-parsing,C#,String Parsing,我试图替换文本文件中与字典中的模式匹配的所有字符串,但我不知道为什么只替换最后一个匹配 我有一个字典,其中第一个值是模式,第二个值是替换值 有人能帮我吗 这是xml文件的一部分。我正在尝试替换匹配的行: <book id="bk101"> <author> ABC</author> <title> DEF</title> <genre> GHI</genre> &l

我试图替换文本文件中与字典中的模式匹配的所有字符串,但我不知道为什么只替换最后一个匹配

我有一个字典,其中第一个值是模式,第二个值是替换值

有人能帮我吗

这是xml文件的一部分。我正在尝试替换匹配的行:

   <book id="bk101">
      <author> ABC</author>
      <title> DEF</title>
      <genre> GHI</genre>
   </book>
这就是我到目前为止所做的:

public static void Update()
{
Dictionary<string, string> items = new Dictionary<string,string>();
    items.Add("<book id=\"bk([0-9]{3})\">", "<TEST 01>");
    items.Add("<author>.+</author>", "<TEST 2>");
    items.Add("<genre>.*</genre>", "");
string contentFile;
string replacedContent = null;

try
{
using (StreamReader sr = new StreamReader(@"C:\Users\acrif\Desktop\log\gcf.xml"))
{
    contentFile = sr.ReadToEnd();
    foreach (KeyValuePair<string, string> entry in items)
    {
    replacedContent = Regex.Replace(contentFile, entry.Key, entry.Value);
    }
    if (replacedContent != null)
    {
    WriteLine("Ok.");
    }
}
using (StreamWriter sw = new StreamWriter(@"C:\Users\acrif\Desktop\log\gcf2.xml"))
{
    sw.Write(replacedContent);
}
}
catch (Exception e)
{
}

}
在你的圈子里

foreach (KeyValuePair<string, string> entry in items)
{
    replacedContent = Regex.Replace(contentFile, entry.Key, entry.Value);
}

您不使用XDocument类的具体原因是什么?或者XmlDocument或XmlReader/XMLWriter实际上不是。我将检查XmlDocument和XmlReader/XmlWriter。谢谢
replacedContent = sr.ReadToEnd();
foreach (KeyValuePair<string, string> entry in items)
{
    replacedContent = Regex.Replace(replacedContent, entry.Key, entry.Value);
}