[英]find and replace in file xml
我想要打開文件xml並找到字符串,然后替換。 但是當替換字符串時只找到兩個字符串並替換我的代碼
var realpath = "~/template/xml/xmlback";
var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/template/xml/xmltest") + ".xml");
var filePath2 = Path.Combine(HttpContext.Current.Server.MapPath("~/template/xml/xmlback/test2") + ".xml");
DirectoryInfo dir = new DirectoryInfo(Path.Combine(HttpContext.Current.Server.MapPath(realpath)));
foreach (FileInfo files in dir.GetFiles())
{
files.Delete();
}
string strVal = System.IO.File.ReadAllText(Server.MapPath("~/template/xml/xmltest") + ".xml");
strVal = strVal.Replace("Test1", "amir");
strVal = strVal.Replace("Test2", "amir1");
strVal = strVal.Replace("Test3", "amir2");
strVal = strVal.Replace("Test4", "amir3");
strVal = strVal.Replace("Test5", "amir4");
strVal = strVal.Replace("Test6", "amir5");
File.Copy(Path.Combine(filePath), Path.Combine(filePath2));
System.IO.File.WriteAllText(Server.MapPath("~/template/xml/xmlback/test2") + ".xml", strVal);
ProcessRequest(filePath2, Lcourseid.Text);
我嘗試用word打開xml並查看結果圖片
我已經使用此代碼解決了我的問題,但是與上面的代碼沒有區別,不是我認為這是一個損壞的文件xml,找不到Test3和Test4,...謝謝大家
Dictionary<string, string> wordsToReplace = new Dictionary<string, string>();
wordsToReplace.Add("Test1", "amir");
wordsToReplace.Add("Test2", "amir1");
wordsToReplace.Add("Test3", "amir3");
wordsToReplace.Add("Test4", "amir4");
wordsToReplace.Add("Test5", "amir5");
wordsToReplace.Add("Test6", "amir6");
string strVal = System.IO.File.ReadAllText(Server.MapPath("~/template/xml/xmltest") + ".xml");
foreach (var pair in wordsToReplace)
{
//Performs each replacement
strVal = strVal.Replace(pair.Key, pair.Value);
}
File.Copy(Path.Combine(filePath), Path.Combine(filePath2));
System.IO.File.WriteAllText(Server.MapPath("~/template/xml/xmlback/test2") + ".xml", strVal);
ProcessRequest(filePath2, Lcourseid.Text);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.