在文件xml中查找和替换

时间:2015-02-01 11:22:07

标签: c# asp.net 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并查看结果pic

1 个答案:

答案 0 :(得分:0)

我已经解决了我的问题 我使用这段代码但与上面的代码没有区别 我认为这是一个损坏的文件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);