简体   繁体   中英

find and replace in file xml

i want open file xml and find string then replace. but when replace string Only to find two strings and replace this my code

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);

im try open xml with word and see result pic

I've solved my issue iam use this code But no difference with the above code does not I think it was a corrupted file xml, Could not find Test3 and Test4,... Thank you all

    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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM