【发布时间】:2018-04-29 16:37:18
【问题描述】:
我正在尝试替换文本文件中与字典中的模式匹配的所有字符串,但我不知道为什么我只替换最后一个匹配项。
我有一个字典,其中第一个值是模式,第二个是替换值。
谁能帮帮我?
这是 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)
{
}
}
【问题讨论】:
-
您不使用 XDocument 类的任何具体原因? (或 XmlDocument 或 XmlReader/XmlWriter)
-
其实不是。我要检查 XmlDocument 和 XmlReader/XmlWriter。谢谢。
标签: c# string-parsing